简体   繁体   中英

Session data lost after page redirect

I'm having problems getting simple session data values to persist after a page redirection. A function checks user data sent via Post and if it matches values in a database it sets session data to the values and redirects to another page:

  if ($login_ok) {
      //set session data                
      $_SESSION ['online'] = 1;
      $_SESSION ['userid'] = $id;
      $_SESSION ['username'] =  $name;
      //redirect to new page
      redirect('start.php');
}

In the new page code the session data is not set. Simple testing returns null values as if the session data wasn't set:

  echo 'Session Login Status: ' . $_SESSION ['online'];
  echo 'Session UserID: ' . $_SESSION ['userid'];
  echo 'Session Username: ' . $_SESSION ['username'];

Replacing the redirect with the above echo statements works correctly. Is the fact that the session data is set and the redirect activated before any page data has loaded mean that the session variables are not assigned?

To ensure an active session is always available, an include file contains this code:

 if (session_status() == PHP_SESSION_NONE) {
    session_start();
  }

Any idea what the issue is here?

Many thanks, Kw

Check if the session is set before progress with

if isset($_SESSION ['online']) and 
    isset($_SESSION ['userid']) and 
    isset($_SESSION ['username'])
{
    echo 'Session Login Status: ' . $_SESSION ['online'];
    echo 'Session UserID: ' . $_SESSION ['userid'];
    echo 'Session Username: ' . $_SESSION ['username'];
} else {
    echo 'Redirect to login or Session expired';
}

Instead of redirect try this

$uid = $_SESSION['USERID'];
if (isset($uid) || $uid != NULL) 
{
 if (!headers_sent()) {
    header('Location:main.php');
    exit;
    }
    else {
    ?>
    <script>window.location = 'main.php';</script>
    <?php
    }
}

This seems to be a server rather than a code issue. Running the code on a localhost server works correctly. Hope this is helpful to people experiencing similar issues.

Saying that, I have no idea how to set the remote server to allow session data. The server has browser based web administration software called cPanel, any suggestions?

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