Including form data in another page - php

When I post my form data:
<form action="layouts.php" method="post">
<input type="text" name="bgcolor">
<input type="submit" value="Submit" align="middle">
</form>
to a php page, "layouts.php", it returns the string, as expected.:
$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"
But when I include "layouts.php" in another page it returns NULL.
<?php
include("php/layouts.php");
echo $bgcolor; //
echo gettype($bgcolor); //returns "NULL"
?>
How do I pass the variable to another page?

You'll have to use a session to have variables float around in between files like that.
It's quite simple to setup. In the beginning of each PHP file, you add this code to begin a session:
session_start();
You can store variables inside of a session like this:
$_SESSION['foo'] = 'bar';
And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions).

layouts.php
<?php
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>
new.php
<?php
session_start();
echo $_SESSION['bgcolor'];
?>

Give the form two action="" and see what happens. I just tried that on a script of mine and it worked fine.
A more proper way to solve this might exist, but that is an option.

Related

Can php session variable be changed, and if so how?

I am totally confused with session variables. I thought that if I set a session variable, then that variable will be available in any php document that begins with session_start. But it's not working.
Form:
<?php
session_start();
if(isset($_POST['hour'])) {
$_SESSION['hour'] = $_POST['hour'];
}
?>
<!DOCTYPE html>
<html>
<body>
<form action='viewA.php' method='post'>
<input type="text" name='hour' value='24'>
<input type ='submit' name= 'submit' value='submit'>
</form>
</body>
</html>
I post to viewA.php, and it works:
<?php
$hour = $_POST['hour'];
echo 'I am view A, and hour is '.$hour;
?>
<html>
<a href='View_B.php'>See View B</a>
<a href='TEST_form.php' >Choose another hour</a>
</html>
The file viewA.php has a link to View_B.php; here's View_B's code:
<?php
session_start();
print_r($_SESSION);
//$hour = $_SESSION['hour'];
//echo '... and in view B, hour is '.$hour;
?>
<html>
<a href='aatestform.php' >Choose another hour</a>
</html>
No matter what I put into the input in the form, the print_r($_SESSION); View_B outputs only Array ( [hour] => 13 ), which is the first hour I chose way back when. I type in "22"; it outputs 13. I type in "08", it outputs 13.
According to w3schools, "To change a session variable, just overwrite it"
What am I doing wrong? Please help!
In your viewA.php you don't store / overwrite the session variable with the $_POST value.
You just do it in your TEST_form.php which doesn't get any $_POST so your if(isset(... is useless.
Your post destination (the action) is viewA.php, this means that your request will be made to viewA.php.
You're using session variabiles only in the form page and in View_B.php.
If you look carefully at your code in ViewA.php, you'll see that you're working only with POST variables, not session variables.
This php code, that you have in your form page
<?php
session_start();
if(isset($_POST['hour'])) {
$_SESSION['hour'] = $_POST['hour'];
}
?>
Should be moved to viewA.php.
Doing this, viewA.php will check if the POST variable "hours" is set. In that case, it overwrite (or create) the session variable "hours".

How to trigger execution of a PHP file within a PHP file

So I have an HTML file that is a basic form. Say
<form method="POST" action="test1.php">
Name: <input type="text" name="name" id="name" />
<input type="submit" value="Submit" />
</form>
Now I have that execute my test1.php file which goes as follows:
<?php
$name = $_POST['name'];
?>
So all it is doing is getting the value from the HTML form. Now I have a second PHP file test2.php that needs to get the value from the first test1.php file $name and output it via an echo statement.
I'm new to PHP and am fine with using one PHP file to output values from an HTML form, but I don't know how to approach a second one.
I'm aware that you can use the include statement to carry over the variables and their values, but it didn't seem to work in my instance. I'm almost positive the issue is that I don't have test2.php actually being executed. And I don't know how to approach that. Any help is appreciated.
EDIT: This is all I want test2.php to do. $name has to be the same value as retrieved from the HTML form in test1.php
<?php
echo $name;
?>
Just use include your file test2.php inside test1.php:
<?php
$name = $_POST['name'];
include('test2.php');
?>
Whenever you include a file using either include() or require(), the file always gets "executed", so maybe there's something else wrong in you code.
EDIT
test1.php:
<?php
$name = $_POST['name'];
include('test2.php');
?>
test2.php:
<?php
echo $name;
?>
I would suggest starting a session in test1, assign the var $name to the session and then picking the session up on test2.
test1.php
session_start();
$name = filter_var($_POST['name'],FILTER_SANITIZE_STRING);
$_SESSION['test1']['name'] = $name;
test2.php
session_start();
$name = $_SESSION['test1']['name'];
Try that.
#bloodyKnuckles, Your assignment was left open ended because there are a number of ways you can accomplish what you're looking to do.
include('test2.php');
Is one option. Another would be
header("Location: test2.php");
exit();
Using the header option, $_SESSION variable would work. If test1.php had any HTML output, you could consider an AJAX call or urlencode() your string.
test1.php
echo 'Click Me';
test2.php
$name = $_GET['name'];
I'm guessing your assignment task was designed to demonstrate various ways to pass values from script to script.
Good Luck

Passing Variables Between Scripts in PHP

I have a simple question, with maybe not so simple of an answer. I want to be able to set a variable in one script and pass that value and variable to another script. Without passing it through the url, and having the ability to pass an array.
So I have index.php in there I have a variable
<?php
$myvariable = '';
<form action=editRecord.php>
do some form actions here and submit moving to editRecord.php
</form>
?>
Now in editRecord.php
<?php
header('Location: go back to index.php);
run functions and edit the Mysql DB
//Ok now here is where I want to assign a value to $myvariable and pass it back to index.php
?>
Is this possible? I am sorry for the amateurish question, but I am very green when it comes to php.
Thank You.
you can set it in the $_SESSION variable:
<?php
session_start();
$_SESSION["myVar"] = "blabla";
....
Of course you can store an array() in this variable too.
Just pass that information in the querystring. Then you can access it via $_GET. If it doesn't exist, just set the value to an empty string or whatever default value you want it to have.
// editRecord.php
<?php
// do db dtuff
header('Location: index.php?myvariable=somevalue');
?>
// index.php
<?php
$myvariable = (isset($_GET['myvariable'])) ? $_GET['myvariable'] : '';
<form action="editRecord.php" >
</form>
?>
You can also use session variables:
// editRecord.php
<?php
session_start();
// do db stuff
$_SESSION['myvariable'] = 'somevalue';
header('Location: index.php');
?>
// index.php
<?php
session_start();
$myvariable = (isset($_SESSION['myvariable'])) ? $_SESSION['myvariable'] : '';
<form action="editRecord.php" >
</form>
?>
You can use sessions, POST data, GET data, cookies and database data.

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

How to keep variable constant even after page refresh in PHP

I'm making a simple hangman application and I have my php file and a separate .txt file holding the words, one on each line.
What I want is for the $word variable to remain constant even after the page refreshes since I was planning on using a GET or POST to get the user's input.
In the example code below I want $word to stay the same after the form is submitted.
I believe it's a simple matter of moving code to another place but I can't figure out where any help for this PHP noob would be appreciated!
wordsEn1.txt:
cat
dog
functions.php:
<?php
function choose_word($words) {
return trim($words[array_rand($words)]);
}
?>
hangman.php:
<?php
include('functions.php');
$handle = fopen('wordsEn1.txt', 'r');
$words = array();
while(!feof($handle)) {
$words[] = trim(fgets($handle));
}
$word = choose_word($words);
echo($word);
echo('<form><input type="text" name="guess"></form>');
?>
use sessions:
session_start(); // in top of PHP file
...
$_SESSION["word"] = choose_word($words);
$_SESSION["word"] will be there on refresh
if you care about the "lifetime", follow also this (put it just before session_start)
session_set_cookie_params(3600,"/");
It will hold an hour for the entire domain ("/")
You could use a hidden input:
<form method="POST">
<input type="text" />
<input type="hidden" name="word" value="<?php echo $word; ?>" />
</form>
...and on the next page:
if(isset($_POST['word'])) {
echo $_POST['word'];
}
Or you could use a PHP $_COOKIE, which can be called forever (but kind of a waste if you just want it on the next page):
setcookie('word', $word, time()+3600, '/');
...and on the next page:
echo $_COOKIE['word'];
Just use hidden type forms for that issue.if we put it into session while page refreshes its hide also. if you can store that value in hidden form field it was stored and retrived any time .

Categories