简体   繁体   中英

PHP session variables getting lost after a header redirect

I cannot figure this out. Sometimes after the redirect (see code below), the session variables are lost. Any ideas?

Note the script is initially called with ?p=1&u=2&k=3. As you can see, the script redirects to itself. The session variables something are lost after the redirect.

<?php

session_start();

if ((isset($_SESSION['p'])) and ($_SESSION['p'] != "")) {
    // do something
} else {
    $_SESSION['p'] = $_GET['p'];
    $_SESSION['w'] = $_SERVER["HTTP_HOST"];
    $_SESSION['u'] = $_GET['u'];
    $_SESSION['k'] = $_GET['k'];

    header("Location: http://".$_SESSION['w'].$_SERVER['PHP_SELF']."");
    exit();
}

?>

Cheers

Copied and pasted your code and it works just fine for me. Do you maybe have some spaces or whatever before your <?php -tag?

I am not sure why it happens.

Probably you have some misconfiguration on your php.ini file.

Or you don't have the right session.save_path or permissions to write there.

But if the problem persists, try this way:

<?php

session_start();

if (!$_SESSION['p']) {
    $_SESSION['p'] = $_GET['p'];
    $_SESSION['w'] = $_SERVER["HTTP_HOST"];
    $_SESSION['u'] = $_GET['u'];
    $_SESSION['k'] = $_GET['k'];
}

//code comes here

?>

In my opinion, this is the way things should be done.

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