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".