user520300
user520300

Reputation: 1527

Session variables are not persisting between page loads

Can someone tell me why the session vars are not passing between pages? They were working up to 2 days ago. Now its not? There is a third party system that logs users in based on the third party system. I direct users to the login page with the return url. The third party system logs a user in and passes their id and a token generated on their end and returns them to my site with the id and the token in the url.

If sessions are not set i try and grab the id and the token from the url and set the sessions. (working) I then generate my own token to validate against the token passed from the third party system (working) when i go to click to another page the sessions i set are not empty (????)

Here is my code:

    <?php
    session_start();

    // FUNCTION TO PASS THE URL THE USER IS ON SO THEY COME 
    // BACk TO THIS PAGE AFTER THE LOG IN. IF APPLICABLE
    function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    } else {
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
    }

    // DESTROY SESSION INFO IF TIMED OUT
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    session_destroy();   // destroy session data in storage
    session_unset();     // unset $_SESSION variable for the runtime
    }

    // SET THE SESSIONS WITH INFO PASSED FROM
    // LOGIN PAGE SENT AS A GET
    if(isset($_SESSION['ID']) && isset($_SESSION['token'])) {}else{
    $_SESSION['ID'] = $_GET['ID'];
    $_SESSION['token'] = $_GET['token'];
    }

    // GENERATE MY TOKEN TO MATCH THE LOGIN SYSTEM TOKEN
    $userIP = $_SERVER['REMOTE_ADDR'];
    $secretkey = 'A Unique Key For The Logged In User Matching the Login System Passed From mydomain.com/login.php';
    $algorithm = 'md5';
    $mm = date('m');
    $dd = date('d');
    $mmdd = $mm.$dd;
    $mytoken = strtoupper(hash($algorithm, $secretkey.$_SESSION['ID'].$userIP.$mmdd));


    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
    // THIS IS WHERE THINGS ARE GOING WRONG
// SESSION token IS NO LONG SET AFTER I Go To another page
// and my token isnt the same any more either because session ID
// is no longer set???
    if($_SESSION['token']==$mytoken){}else{
    header("location: https://mydomain.com/login.php?returnURL=".curPageURL());
    }
    ?>

ok this is messed up. It has to be a problem on the hosting providers PHP setup i think because i created two pages. one called info with this code:

<?
session_start();

$_SESSION['ID'] = "112233";
$_SESSION['token'] = "mytoken";

print $_SESSION['ID'];
print $_SESSION['token'];
?>
<a href="info2.php">info 2</a>

and one called info2 with this code:

<?
session_start();

print $_SESSION['ID'];
print $_SESSION['token'];
?>
<a href="info.php">info</a>

info created and printed the session ok. when i click the link to go to info2 the sessions dont print. Is this a hosting config problem?

Upvotes: 27

Views: 74712

Answers (16)

Fran&#231;ois
Fran&#231;ois

Reputation: 987

I had this issue recently and for me this was a silly error. Make sure the session.save_path variable in php.ini is pointing to the correct place.

Upvotes: 0

Jonas
Jonas

Reputation: 1

JFC moment for me;

$_SESSION[""] worked

$_session[""] failed

Upvotes: 0

user6096790
user6096790

Reputation: 430

In case this helps others:

  1. If sessions are closed (e.g. with session_write_close() or session_commit()), then anything written to a session after that is not persisted.

  2. Re-opening a closed session during the same request seems at best an uncertain endeavor. If anything has been sent back to the client already, session_start() seems to fail (return false) and nothing written to $_SESSION is persisted even if errors are not thrown.

Some may wonder why one would close sessions intentionally in the first place - the reason is "performance". Session resources (e.g. files with file-based sessions) are locked while the session is "open" and so for the duration of handling a request by default unless the session is specifically closed. If a response is taking awhile on the server (e.g. a long-running report query), a user (or multi-threaded UI) cannot complete another session-locking request while one is already in progress - so effectively all the session-based requests stack up sequentially and users are stuck waiting (the opposite of what is wanted with most modern UIs). The best answer, in most of my cases, is to release (close) the session as soon as possible (typically just after is has been read for the first time when handling a request) and keep it open for the duration of the request handling only if one needs to write to the session later (cases which should be minimized for performance of course).

Upvotes: 0

Alexandros Kourtis
Alexandros Kourtis

Reputation: 629

If the above solutions do not work I suggest you do the following right before you set the new session variables:

    session_destroy();
    session_start();

and THEN save the new session variables that were not persisting before

Upvotes: 0

Matt Campbell
Matt Campbell

Reputation: 174

For anyone else searching this in frustration - another thing to check is the cookie_secure setting in php.ini.

If cookie_secure=1, cookies will only be sent and persist on secure connections. In our case, the site was deployed to an environment that did not have an ssl setup yet.

Set cookie_secure back to its default (0) - or get the site secured.

Upvotes: 3

Garrick Crouch
Garrick Crouch

Reputation: 329

I had session.cookie_samesite = "Strict" in my runtime file and was trying to bounce my user from Oauth2.0 back to my site and the PHP session ID was getting erased when the redirects hit. I removed this from my runtime file and it works fine now.

Upvotes: 1

eldhose
eldhose

Reputation: 101

The only answer for this problem is to use session_start(); on the top of every page. It will work fine. Else you might need to contact your hosting provider about this problem.

Upvotes: 3

bpile
bpile

Reputation: 380

I would add that I got caught up with the same problem, except that in my case page was behind Varnish caching proxy and I missed out that configuration had a line where cookies were allowed only on specific paths, otherwise they would get removed with the following directive:

unset req.http.cookie;

Dont forget to also check your proxy settings.

Upvotes: 1

D.Sari
D.Sari

Reputation: 31

In my case the solution was to have different parameter names in $_GET and $_SESSION.

$_SESSION["businessid"] = $_GET["businessid"]; // Leads to problems with session. $_SESSION["business_id"] = $_GET["businessid"]; //Works perfectly.

It sounds strange but that's my experience.

Upvotes: 2

grayob
grayob

Reputation: 335

Check the size of the session file: (code taken from this post)

$sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id();  
echo 'session file: ', $sessionfile, ' ';  
echo 'size: ', filesize($sessionfile), "\n";

If your session file has zero size, make sure there is still disk space available on your server. That was the problem I had.

Check disk space with df -h on a linux server.

Upvotes: 4

user3225121
user3225121

Reputation: 21

Make sure both pages are on the same domain. Even www.site.com is different than site.com

Upvotes: 0

Hemant Jadhav
Hemant Jadhav

Reputation: 95

it's not the hosting server issue...

check your URLs

if a user is login under "example.com" session will be stored for "example.com" and not "WWW.example.com" so if a link goes to www.example.com it will not have that session.

you can use htaccess to always set the url to "WWW.example.com" use below code for it

RewriteEngine On

RewriteCond %{HTTP_HOST} ^hemantjadhav.com$ [NC]

RewriteRule ^(.*)$ http://www.hemantjadhav.com/$1 [L,R=301]

(replace hemantjadhav with your domain name)

Upvotes: 6

user520300
user520300

Reputation: 1527

The answer to this is it was a hosting configuration error. Hosting company changed something and it has worked ever since.

Upvotes: 3

Rudi Visser
Rudi Visser

Reputation: 21969

As already mentioned, ensure you're calling session_start() on each page.

Additionally, are the scripts on different subdomains?? If they are you should set the INI value session.cookie_domain to .DOMAIN.EXT.

To further debug this whole situation, do some simple cookie watching. See if PHPSESSID is present as a cookie on both page requests, if it's not then this is your problem. You can't store cookies cross-domain unless you reconstruct them.


In response to your update, try doing this underneath your call to session_start():

echo session_id();

Confirm that it's the same on both pages. If not, check the value of session.cookie_domain like this:

echo ini_get('session.cookie_domain');

Is that set to anything? By default it should be blank, if it's set, especially not to your domain, this is the problem.

You can also try debugging the cookie value of PHPSESSID like I first suggested.

Upvotes: 23

Jagadeesan
Jagadeesan

Reputation: 1097

Check List
1. Make sure that you have used session_start(); in the next page.

2. Are you using .htaccess file?
    if so remove the .htaccess file and check the same.
    some time rewrite rules cause session probs...

3. If session is working fine and you have trouble only with token, then check the token sent in url is url_encoded.

Upvotes: 12

Jage
Jage

Reputation: 8086

You did not call session_write_close()

Upvotes: -1

Related Questions