DevSael Blog. C, CPP, C++, PHP, .NET Programming BLOG! advanced, MySQL, MongoDB, RDBMS.

Browsing "Older Posts"



Q. PHP Session variable value is not transfering?

So, you are having trouble with php session variables! Well, Let see how can it being solved! If you didn't read about PHP Session variables then have a look on the manual!

Well let see what is happening...

PHP file: <test1.php>

<?PHP
session_start();

header("Access-Control-Allow-Origin: *"); 
header("Content-Type: application/json; charset=UTF-8");

//some code to determine $approvedToSet
$approvedToSet = true;
if(isset($approvedToSet))
{
$_SESSION["userName"] = 'MyName'; 
echo " Session variable is set." .$_SESSION["userName"];
} 
else { 
echo "User name is not set";} 

?>

PHP file: <test2.php>

<?PHP
echo $_SESSION["userName"];

ERROR:

Notice: Undefined index: userName in /var/www/xyz on line 30


[Solution:]

Correct Your file and ensure session_start(); function is on the top of your page.

PHP file: <test2.php>

<?PHP
session_start()
echo $_SESSION["userName"]; ?>

  1. Stop your apache2 or http server and start it again!
  2. Ensure session.save_path has been set.
  3. Must be Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?phptag.
  4. After the header redirect, end the current script using exit(); (Others have also suggestedsession_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
  5. Make sure cookies are enabled in the browser you are using to test it on.
  6. Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
  7. Make sure you didn't delete or empty the session.
  8. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
  9. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  10. Make sure your file extension is .php (it happens!).
  11. If you use a connection script, dont forget to use start_session(); at the connection too, had some trouble before noticing that issue.
iu

[SOLVED] PHP Session variable value doesn't retrieved to another page

By Game Changer → Friday, May 5, 2017