简体   繁体   中英

Cannot set php session variable to another php page

I cannot set a session variable on one page to another my code is below.

first page

session_start();
header('Content-Type: application/json;charset=utf-8');

///mysql connections
while($row = mysql_fetch_array( $sthpre )){
// Print out the contents of each row into a table

$rows[] = $row; 
$_SESSION['id']=$row['id'];
print json_encode($row);

}//still i get null on the other page $_SESSION['id'] = 22;

second page

session_start();
header('Content-Type: application/json;charset=utf-8');
$row['id']=$_SESSION['id'];
print json_encode($row);

Try that:

session_start();

session_regenerate();

header('Content-Type: application/json;charset=utf-8');

$row['id']=$_SESSION['id']; print json_encode($row);

Based off of the knowledge that you have a different session id in each page my guess is that the directory that php is trying to use to store sessions is not writable by the apache user. If you create a page and put:

session_save_path();

It will tell you where php is trying to write the session information on the server. Make sure the directory it displays to you is writable by the apache user (most likely www-data). Or change it to a different directory that is writable. You can do it in your code like this:

session_save_path('/tmp');

Or you can change it in your php.ini file.

If that isn't the issue and it is because your app isn't maintaining a consistent session id you can force a session_id.

session_start();
session_id('5468313'); //any random id

Just do this in both files however you will need to generate a different session id for each person who logs in otherwise everyone will be sharing the same session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM