Using A session, what went wrong

They have: 4 posts

Joined: Aug 2014

I am not able to get my email input even after defining my sessions, please look below:
I have two scripts: The first is is to show the declaration of the session, while the second is to display the session's value:
First Script:sessionTest1.php

<?php
session_start
();
?>

<html>
<head><title>Testing Sessions page 1</title></head>
<body>
<?php
$_SESSION
['session_var'] = "testing";
@
$_SESSION['session_var2'] = $_POST['email'];
echo
"This is a test of the sessions feature.
<form action='sessionTest2.php' method='POST'>
<input type='hidden' name='form_var'
value='testing'>
<input type='text' name='email'>
<input type='submit' value='go to next page'>
</form>"
;
?>

</body></html>

Second Script:sessionTest2.php

<?php
session_start
();
?>

<html>
<head><title>Testing Sessions page 2</title></head>
<body>
<?php
echo "session_var = {$_SESSION['session_var']}<br>\n";
echo
"session_var2 = {$_SESSION['session_var2']}<br>\n";
echo
"form_var = {$_POST['form_var']}<br>\n";
?>

</body></html>

Please what could be possibly wrong? or what should i do to obtain the entered value for the email and then be able to pass it along to as many pages as possible?

[Mod Edit: adjusted the code highlighting for the post]

Greg K's picture

He has: 2,140 posts

Joined: Nov 2003

First things first.... Do NOT use @ on a line unless you have a good reason. If you are using that, it usually means that you are not using good coding practices. In your code, you are using it to hide the warning that $_POST['email'] is set. This is just a big no-no in terms of good programming.

For this, instead you should actually be checking if it exists:

$_SESSION['session_var2'] = (isset($_POST['email'])) ? $_POST['email'] : FALSE;

Now onto the main issue you are having: You are having the form submit to sessionTest2.php, that is the script that will see $_POST['email']. There first one would only see it if you were coming from another page that had a form and it was set to post to it.

So move your session setting code for e-mail down to the second script, and it should set the session properly for you and then be available anywhere else the session is alive.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.