Session variables are not persisting between page loads
Asked Answered
B

16

27

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?

Bedroom answered 1/6, 2011 at 11:48 Comment(1)
I am having the exact same problem ... except my stuff is on localhost, using PHP with IISRoaring
B
3

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

Bedroom answered 22/8, 2011 at 1:51 Comment(2)
It would be nice to know what it was.Tremain
it my case it was also hosting issue it was htaccess file they modified and added some new rules for specific php versions, it seems htaccess was creating confution between pages and php versions installed in serverWindom
W
23

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.

Woolworth answered 1/6, 2011 at 12:25 Comment(5)
see my addition to the orig postBedroom
i havent tried this yet but will. Question... if by default echo ini_get('session.cookie_domain'); is not blank and its not my domain what do i do?Bedroom
2 Options, 1: Contact your hosting provider because it's wrong, 2: You can use ini_set('session.cookie_domain', '.your.domain'); or ini_set('session.cookie_domain', ''); before session_start().Woolworth
As already mentioned, ensure you're calling session_start() on each page., always the simple answer that elludes me. Cheers Rudi, kudos points for you!!Mccreary
I've checked all these and still can't get Session to persist. I see PHPSESSID set, but my $_SESSION variables are not carrying to next page load.Blather
C
12

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.

Counterman answered 1/6, 2011 at 12:16 Comment(2)
i have checked the addition. this problem might be because of server configuration. check with your hosting provider.Counterman
Indeed, having the .htaccess file was causing my session_start() to fail and return false. Wow, that is really subtle and insidious! Thx it works now.Andesine
C
6

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)

Charmeuse answered 17/7, 2013 at 12:9 Comment(1)
That was it, check your URLS! I was pulling my hair out and did not realize that I was storing from two different sites. One with www and one without.Inform
P
4

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.

Photoconductivity answered 22/8, 2012 at 14:52 Comment(1)
thanks to you I saw my folder didnt have the correct access right.Heymann
B
3

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

Bedroom answered 22/8, 2011 at 1:51 Comment(2)
It would be nice to know what it was.Tremain
it my case it was also hosting issue it was htaccess file they modified and added some new rules for specific php versions, it seems htaccess was creating confution between pages and php versions installed in serverWindom
C
3

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.

Conspectus answered 12/9, 2019 at 16:21 Comment(2)
When answering an eight year old question with nine existing answers it is useful to explain what new aspect of the question your answer addresses. Also note if the answer would have worked when the question was asked, or if it depends on something that has changed over those eight years.Vhf
session_start() is set in OPs code examples. did you even read before answering?Berserk
R
3

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.

Roux answered 3/6, 2021 at 14:15 Comment(0)
S
2

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.

Soot answered 12/3, 2019 at 11:4 Comment(0)
I
1

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.

Iives answered 12/4, 2019 at 15:23 Comment(0)
M
1

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.

Madelina answered 22/2, 2020 at 5:2 Comment(0)
B
0

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

Bettiebettina answered 17/2, 2014 at 12:34 Comment(0)
O
0

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

Odom answered 14/11, 2021 at 7:26 Comment(0)
H
0

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).

Heroin answered 23/11, 2022 at 22:53 Comment(0)
T
0

JFC moment for me;

$_SESSION[""] worked

$_session[""] failed

Tripinnate answered 29/3, 2023 at 11:24 Comment(1)
Hi, original question was 11 years ago... And already has accepted answer. Be sure to add some valuable info while answering. Thank you, and read how to answerFavors
E
0

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.

Epiphenomenalism answered 14/7, 2023 at 15:19 Comment(0)
F
-1

You did not call session_write_close()

Fleeman answered 1/6, 2011 at 11:52 Comment(5)
It would likely be at the very end of your script. It writes session data and closes the session, so whenever you're done with session stuff is fine. I only suggest the very end since session_start() is the very first thing you do.Fleeman
tried... didnt work. when i go click to go to another page my sessions are empty stillBedroom
He doesn't need to do this at all.Woolworth
Concurring with @rudi_visser: php.net/session_write_close - "Session data is usually stored after your script terminated without the need to call session_write_close()".Lichenin
see my addition to the orig postBedroom

© 2022 - 2024 — McMap. All rights reserved.