Reputation: 81
Am new to PHP Sessions and facing problem in passing session variable.Couldn't figure out what is the problem in this code. Page1
<html>
<head><title>My First PHP</title></head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION = "main1.php">
<table >
<tr><td>First Name: <INPUT TYPE = "TEXT" VALUE ="" NAME = "first"></td></tr>
<tr><td>Last Name: <INPUT TYPE = "TEXT" VALUE ="" NAME = "last"></td></tr>
<tr><td><INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click Here"></td></tr></table>
</FORM>
<?php
session_start();
if(isset($_POST['Submit1']) ){
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$firstname=ucwords($firstname);
$_SESSION["firstname"] = $_POST['first'];
$_SESSION["lastname"] = $_POST['last'];
echo $_SESSION["firstname"] ."-" . $_SESSION["lastname"] ;
echo "Hello, ".$firstname. " " .$lastname ."!" . "<br>";
}
?>
</body>
</html>
page 2
<html>
<head><title>My second PHP</title></head>
<body>
<?php
session_start();
$first = $_POST["first"];
$last = $_POST["last"];
$first = ucwords($first);
$last = ucwords($last);
$firstname = $_SESSION["firstname"];
echo $firstname;
?>
<FORM NAME ="form1" METHOD ="POST" ACTION = "main1.php">
<table align="center" >
<tr><td>First Name: <INPUT TYPE = "TEXT" NAME = "first" VALUE="<?php echo htmlentities($first); ?>"/></td></tr>
<tr><td>Last Name: <INPUT TYPE = "TEXT" VALUE ="<?php echo htmlentities($last); ?>" NAME = "last"></td></tr>
</table>
</FORM>
</body>
</html>
Here am unable to access the $firstname using SESSION. Can someone help what is the issue?
Undefined index: firstname is th error.Have checked many posts regarding this but still the error persists.
Upvotes: 0
Views: 1644
Reputation: 93
Look, from your code, your session variable is being initialized after sending the data, I mean after clicking the submit button of your first page. But when you send the from it is going to the next page without initialize the session variable. That's mean the session variable is not being initialized. So, you can create another page which is linked up between this two page. Create another page named linkingPage.php. Change the first page action to linkingPage.php and cut those lines php code and paste it to the newly created page
<?php
session_start();
if(isset($_POST['Submit1']) ){
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$firstname=ucwords($firstname);
$_SESSION["firstname"] = $_POST['first'];
$_SESSION["lastname"] = $_POST['last'];
header('Location:main1.php');
}
?>
last two line is commented out, cause now it's unnesseceray. Now run the code and I hope it will work. Enjoy.
Upvotes: 3
Reputation: 187
A session variable can be used throughout the website, on any page
However, could this be an error with your POST? try simply setting the session variables to a string, and see if they are retrieved on the other webpage
Upvotes: 0