PHP session_id( ) null - php

I am having some difficulty with sessions.
On my local MAMP test server, if I do:
session_start( );
echo session_id( );
I get a nice looking session id.
If However, I the same thing on my web server, all I can get back from session_id is 'null'. Testing the return from session_start( ) and using sessions everything is working, but session_id( ) $SID and $PHPSESSID are all null.
Is this hidden on purpose for added security? I want to be able to allow flash to make changes to a shopping cart through PHP calls and have the cart (which is stored in the session) reflected using the browser.

Make sure the return value of session_start() is TRUE.
Make sure you are calling session_start() before your script outputs anything to the browser.
Check that apache has write access to the session path. Mine is /tmp

I had a similar problem (session_id() returned "", I hope, this is related to your question). I closed all corresponding tabs and deleted all relevant cookies, then re-opened the site and now session_id() returns a beautiful hash value.

Perhaps an edge case, but for me, I solved it by testing the return value of session_start() which showed it to be false.
The issue turned out to be the encoding of the actual file. It was emitting something invisible before the session started, even though it looked like nothing was there.
I solved it by copying the relevant files into a plain text editor (I used https://www.editpad.org/), deleting the source file on, recreating the empty file, pasting that code I had run through editpad, and reuploading.
After that everything started populating normally.

I had a similar issue on Windows and for me it was caused by the ini setting session.save_path having an invalid path defined.

Related

PHP session variables lost after header() redirect [duplicate]

How do I resolve the problem of losing a session after a redirect in PHP?
Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).
Update
I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.
First, carry out these usual checks:
Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();)
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
Make sure your file extension is .php (it happens!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
I tried all possible solutions, but none worked for me! Of course, I am using a shared hosting service.
In the end, I got around the problem by using 'relative url' inside the redirecting header !
header("location: http://example.com/index.php")
nullified the session cookies
header("location: index.php")
worked like a charm !
I had the same problem. I worked on it for several hours and it drove me crazy.
In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.
I was having the same problem. All of a sudden SOME of my session variables would not persist to the next page. Problem turned out to be ( in php7.1) you header location must not have WWW in it, ex https://mysite. is ok, https://www.mysite. will lose that pages session variables. Not all, just that page.
When i use relative path "dir/file.php" with in the header() function in works for me.
I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")
I had a similar problem, although my context was slightly different.
I had a local development setup on a machine whose hostname was windows and IP address was 192.168.56.2.
I could access the system using either of:
http://localhost/
http://127.0.0.1/
http://windows/
http://192.168.56.2/
After logging in, my PHP code would redirect using:
header('http://windows/');
If the previous domain name used to access the system was not windows, the session data would be lost. I solved this by changing the code to:
header('http://'.$_SERVER['HTTP_HOST'].'/');
It now works regardless of what local domain name or IP address the user puts in.
I hope this may be useful to someone.
I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.
Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:
function sessionKill(){
session_destroy();
}
to:
function sessionKill(){
session_destroy();
session_start();
}
And everything worked!
This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:
session.use_cookies = 1
I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.
I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.
So don't forget that!
Nothing worked for me but I found what caused the problem (and solved it):
Check your browser cookies and make sure that there are no php session cookies on different subdomains (like one for "www.website.com" and one for "website.com").
This was caused by a javascript that incorrectly used the subdomain to set cookies and to open pages in iframes.
KEY POINT'S
Do not start a session on the return page.
Don't use session variable and not include header.php which user session variable
Just make a link go to home page or profile page after insert payment info and status
I had the same problem and found the easiest way.
I simply redirected to a redirect .html with 1 line of JS
<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>
instead of PHP
header_remove();
header('Location: admin_login.php');
die;
I hope this helps.
Love
Gram
If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.
The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.
Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.
So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.
Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.
Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me
To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.
Verify that your session is not Strict. If it is, when you come back, like coming back from Stripe, it regenerate the session.
Use This:
ini_set('session.cookie_samesite', 'Lax');
I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.
I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.
signin.php
if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);
signin_action.php
<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {
echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}
?>
It is not a beautiful work-around but it worked.
For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.
Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...
For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter.
So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.
After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]
If you're using Wordpress, I had to add this hook and start the session on init:
function register_my_session() {
if (!session_id()) {
session_start();
}
}
add_action('init', 'register_my_session');
First of all, make sure you are calling session_start() before using $_SESSION variable.
If you have disabled error reporting, try to turn in on and see the result.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The most common reasons that aren't mentioned in #dayuloli's answer:
Disk space problem. Make sure your disk space is not full, you need some space to store session files.
Session directory may not be writable. You can check it with is_writable(session_save_path())
I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.
So, if someone reads this, please check php.ini config before anything else.
Make sure session_write_close is not called between session_start() and when you set your session.
session_start();
[...]
session_write_close();
[...]
$_SESSION['name']='Bob'; //<-- won't save
If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.
session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.
I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.
You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.
I fixed this problem after many days of debugging and it was all because my return URL coming from PayPal Express Checkout didn't have a 'www'. Chrome recognized that the domains should be treated the same but other browsers sometimes didn't. When using sessions/cookies and absolute paths, don't forget the 'www'!

PHP Session's Data is inconsistent between page reloads - the Session ID is the same though

I'm having a really strange problem with some of my PHP code. I have error reporting turned on and nothing's coming up either.
Basically I have a form that pushed data to $_SESSION[]. The code is:
<?php
session_start();
$_SESSION['contact']['name'] = $_GET['name'];
$_SESSION['contact']['email'] = $_GET['email'];
$_SESSION['contact']['question'] = $_GET['question'];
session_write_close();
header('Location: confirm.php');
exit;
?>
This is working. However, completely at random the confirm.php will or will not recieve this data. If I refresh multiple times I sometimes get the data, sometimes not.
Here's the confirm code:
<?php
ini_set('display_errors', 'on');
error_reporting(-1);
session_start();
print "SeshID:" . session_id() . "<br>";
print "CookieID:" . $_COOKIE['PHPSESSID'] . "<br>";
print "Status" . session_status() . "<br>";
print "Loc" . session_save_path() . "<br>";
print "Cookie";
print_r(session_get_cookie_params());
print "<br>Data:<br>";
print_r($_SESSION);
?>
Again, no errors. Nothing appearing that looks obviously wrong.
The strange thing is that sometimes when I refresh the confirm page I will get an empty "Array ( )". Sometimes I'll get "Array ( [contact] => Array ( [question] => test [name] => [email] => test#test.com) )" for seemingly no reason...
I'm running no other scripts in between doing this - only the script above that checks the content of the session (confirm) need be re-ran and only the data somehow changes. I run the form a few times, then this check script and it's entirely inconsistent. The session and cookie IDs never change and are always the same
Is there some PHP setting I'm missing? It's really weird to me that these are seemingly pulling out old data which has been overwritten.
Solved!
I'll post my own answer for people with the same problem. Thanks to the people who helped in the comments for discovering this for me!
The Problem
The problem was that the server was using a cluster or distribution network, mine Azure, to serve the PHP files.
The first call writes the session data to machine 1, and the confirm is then reading from machine 2, which doesn't have the right info. In clusters, /tmp is often not mirrored, and that is where the session data is stored. Talk to your cluster admin about this. – Bart Friederichs
It seems like the form was being sent and having the session variables stored on server 1, but the page pulling the session data was server 2, server 3 and sometimes server 1 - hence the odd behaviour of seeing prior submissions and occasionally correct data.
The Fix
There are two possible fixes here. One:
The session store directory isn't being mirrored across all servers
In this case, change your session directory by changing "session.save_path" in your php.ini or by using
session_save_path(dirname(__FILE__). '/sessions/');
at the top of the affected files before you call session_start() (this was the ONLY part of our site that uses sessions so this made for a good / dirty fix).
The point here is to change it to a directory that is for sure being mirrored across every server in your cluster.
The session is being saved in another way that isn't mirrored
In my actual case I found that my session handler was the problem. By using
phpinfo();
I found that my session.save_handler was "wincache", which is a plugin to speed up PHP. One of the ways it appears to do this is by using shared memory or something in order to speed up the loading of the session data.
Either way, this was not right for my setup and I fixed it by simply changing the variable to use the default: 'files'.
Again, the best way to do this is by using your php.ini and setting session.save_handler to "files" but I don't have access to that file and so, again, I just used a call in the header of the two files before session_start().
ini_set("session.save_handler", "files");
I wouldn't recommend this as you know it's going to come up and bite you in the backside later on when a new developer comes in and you forget - it's better to change your .ini
Anyway, that was that.
Thanks everyone for your help!
Aside
Many server solutions such as Azure actually offer their own plugins and session handlers specifically to counteract this kind of situation. If possible you should of course use them!
After refreshing the page the session is still authenticated, but we lose the things we've added manually using the instruction
try this one
(this.set('session.X', 'Y'));

Why won't my $_SESSION variable change for each field [duplicate]

How do I resolve the problem of losing a session after a redirect in PHP?
Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).
Update
I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.
First, carry out these usual checks:
Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();)
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
Make sure your file extension is .php (it happens!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
I tried all possible solutions, but none worked for me! Of course, I am using a shared hosting service.
In the end, I got around the problem by using 'relative url' inside the redirecting header !
header("location: http://example.com/index.php")
nullified the session cookies
header("location: index.php")
worked like a charm !
I had the same problem. I worked on it for several hours and it drove me crazy.
In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.
I was having the same problem. All of a sudden SOME of my session variables would not persist to the next page. Problem turned out to be ( in php7.1) you header location must not have WWW in it, ex https://mysite. is ok, https://www.mysite. will lose that pages session variables. Not all, just that page.
When i use relative path "dir/file.php" with in the header() function in works for me.
I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")
I had a similar problem, although my context was slightly different.
I had a local development setup on a machine whose hostname was windows and IP address was 192.168.56.2.
I could access the system using either of:
http://localhost/
http://127.0.0.1/
http://windows/
http://192.168.56.2/
After logging in, my PHP code would redirect using:
header('http://windows/');
If the previous domain name used to access the system was not windows, the session data would be lost. I solved this by changing the code to:
header('http://'.$_SERVER['HTTP_HOST'].'/');
It now works regardless of what local domain name or IP address the user puts in.
I hope this may be useful to someone.
I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.
Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:
function sessionKill(){
session_destroy();
}
to:
function sessionKill(){
session_destroy();
session_start();
}
And everything worked!
This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:
session.use_cookies = 1
I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.
I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.
So don't forget that!
Nothing worked for me but I found what caused the problem (and solved it):
Check your browser cookies and make sure that there are no php session cookies on different subdomains (like one for "www.website.com" and one for "website.com").
This was caused by a javascript that incorrectly used the subdomain to set cookies and to open pages in iframes.
KEY POINT'S
Do not start a session on the return page.
Don't use session variable and not include header.php which user session variable
Just make a link go to home page or profile page after insert payment info and status
I had the same problem and found the easiest way.
I simply redirected to a redirect .html with 1 line of JS
<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>
instead of PHP
header_remove();
header('Location: admin_login.php');
die;
I hope this helps.
Love
Gram
If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.
The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.
Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.
So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.
Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.
Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me
To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.
Verify that your session is not Strict. If it is, when you come back, like coming back from Stripe, it regenerate the session.
Use This:
ini_set('session.cookie_samesite', 'Lax');
I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.
I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.
signin.php
if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);
signin_action.php
<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {
echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}
?>
It is not a beautiful work-around but it worked.
For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.
Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...
For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter.
So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.
After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]
If you're using Wordpress, I had to add this hook and start the session on init:
function register_my_session() {
if (!session_id()) {
session_start();
}
}
add_action('init', 'register_my_session');
First of all, make sure you are calling session_start() before using $_SESSION variable.
If you have disabled error reporting, try to turn in on and see the result.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The most common reasons that aren't mentioned in #dayuloli's answer:
Disk space problem. Make sure your disk space is not full, you need some space to store session files.
Session directory may not be writable. You can check it with is_writable(session_save_path())
I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.
So, if someone reads this, please check php.ini config before anything else.
Make sure session_write_close is not called between session_start() and when you set your session.
session_start();
[...]
session_write_close();
[...]
$_SESSION['name']='Bob'; //<-- won't save
If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.
session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.
I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.
You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.
I fixed this problem after many days of debugging and it was all because my return URL coming from PayPal Express Checkout didn't have a 'www'. Chrome recognized that the domains should be treated the same but other browsers sometimes didn't. When using sessions/cookies and absolute paths, don't forget the 'www'!

PHP session lost after redirect

How do I resolve the problem of losing a session after a redirect in PHP?
Recently, I encountered a very common problem of losing session after redirect. And after searching through this website I can still find no solution (although this came the closest).
Update
I have found the answer and I thought I'd post it here to help anyone experiencing the same problem.
First, carry out these usual checks:
Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php declaration before anything else. Also ensure there are no whitespaces/tabs before the opening <?php declaration.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();)
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
Make sure your file extension is .php (it happens!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
I tried all possible solutions, but none worked for me! Of course, I am using a shared hosting service.
In the end, I got around the problem by using 'relative url' inside the redirecting header !
header("location: http://example.com/index.php")
nullified the session cookies
header("location: index.php")
worked like a charm !
I had the same problem. I worked on it for several hours and it drove me crazy.
In my case the problem was a 404 called due to a missing favicon.ico in Chrome and Firefox only. The other navigators worked fine.
I was having the same problem. All of a sudden SOME of my session variables would not persist to the next page. Problem turned out to be ( in php7.1) you header location must not have WWW in it, ex https://mysite. is ok, https://www.mysite. will lose that pages session variables. Not all, just that page.
When i use relative path "dir/file.php" with in the header() function in works for me.
I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")
I had a similar problem, although my context was slightly different.
I had a local development setup on a machine whose hostname was windows and IP address was 192.168.56.2.
I could access the system using either of:
http://localhost/
http://127.0.0.1/
http://windows/
http://192.168.56.2/
After logging in, my PHP code would redirect using:
header('http://windows/');
If the previous domain name used to access the system was not windows, the session data would be lost. I solved this by changing the code to:
header('http://'.$_SERVER['HTTP_HOST'].'/');
It now works regardless of what local domain name or IP address the user puts in.
I hope this may be useful to someone.
I ran into this issue on one particular page. I was setting $_SESSION values in other pages right before redirecting and everything was working fine. But this particular page was not working.
Finally I realized that in this particular page, I was destroying the session at the beginning of the page but never starting it again. So my destroy function changed from:
function sessionKill(){
session_destroy();
}
to:
function sessionKill(){
session_destroy();
session_start();
}
And everything worked!
This stumped me for a long time (and this post was great to find!) but for anyone else who still can't get sessions between page redirects to work...I had to go into the php.ini file and turn cookies on:
session.use_cookies = 1
I thought sessions worked without cookies...in fact I know they SHOULD...but this fixed my problem at least until I can understand what may be going on in the bigger picture.
I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.
So don't forget that!
Nothing worked for me but I found what caused the problem (and solved it):
Check your browser cookies and make sure that there are no php session cookies on different subdomains (like one for "www.website.com" and one for "website.com").
This was caused by a javascript that incorrectly used the subdomain to set cookies and to open pages in iframes.
KEY POINT'S
Do not start a session on the return page.
Don't use session variable and not include header.php which user session variable
Just make a link go to home page or profile page after insert payment info and status
I had the same problem and found the easiest way.
I simply redirected to a redirect .html with 1 line of JS
<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>
instead of PHP
header_remove();
header('Location: admin_login.php');
die;
I hope this helps.
Love
Gram
If you are using session_set_cookie_params() you might want to check if you are passing the fourth param $secure as true. If you are, then you need to access the url using https.
The $secure param being true means the Session is only available within a secure request. This might affect you locally more than in stage or production environments.
Mentioning it because I just spent most of today trying to find this issue, and this is what solved it for me. I was just added to this project and no one mentioned that it required https.
So you can either use https locally, or you can set the $secure param to FALSE and then use http locally. Just be sure to set it back to true when you push your changes up.
Depending on your local server, you might have to edit DocumentRoot in the httpd-ssl.conf of the server so that your local url is served https.
Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me
To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.
Verify that your session is not Strict. If it is, when you come back, like coming back from Stripe, it regenerate the session.
Use This:
ini_set('session.cookie_samesite', 'Lax');
I also had the same issue with the redirect not working and tried all the solutions I could find, my header redirect was being used in a form.
I solved it by putting the header redirect in a different php page 'signin_action.php' and passing the variables parameters through I wanted in url parameters and then reassigning them in the 'signin_action.php' form.
signin.php
if($stmt->num_rows>0) {
$_SESSION['username'] = $_POST['username'];
echo '<script>window.location.href = "http://'.$root.'/includes/functions/signin_action.php?username='.$_SESSION['username'].'";</script>';
error_reporting(E_ALL);
signin_action.php
<?php
require('../../config/init.php');
$_SESSION['username'] = $_GET['username'];
if ($_SESSION['username']) {
echo '<script>window.location.href = "http://'.$root.'/user/index.php";</script>';
exit();
} else {
echo 'Session not set';
}
?>
It is not a beautiful work-around but it worked.
For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.
Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...
For me, Firefox has stored session id (PHPSESSID) in a cookie, but Google Chrome has used GET or POST parameter.
So you only have to ensure that the returning script (for me: paypal checkout) commit PHPSESSID in url or POST parameter.
After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]
If you're using Wordpress, I had to add this hook and start the session on init:
function register_my_session() {
if (!session_id()) {
session_start();
}
}
add_action('init', 'register_my_session');
First of all, make sure you are calling session_start() before using $_SESSION variable.
If you have disabled error reporting, try to turn in on and see the result.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
The most common reasons that aren't mentioned in #dayuloli's answer:
Disk space problem. Make sure your disk space is not full, you need some space to store session files.
Session directory may not be writable. You can check it with is_writable(session_save_path())
I was having the same problem and I went nuts searching in my code for the answer. Finally I found my hosting recently updated the PHP version on my server and didn't correctly set up the session_save_path parameter on the php.ini file.
So, if someone reads this, please check php.ini config before anything else.
Make sure session_write_close is not called between session_start() and when you set your session.
session_start();
[...]
session_write_close();
[...]
$_SESSION['name']='Bob'; //<-- won't save
If you are using Laravel and you experience this issue, what you need is to save your session data before redirecting.
session()->save();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.
I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.
You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.
I fixed this problem after many days of debugging and it was all because my return URL coming from PayPal Express Checkout didn't have a 'www'. Chrome recognized that the domains should be treated the same but other browsers sometimes didn't. When using sessions/cookies and absolute paths, don't forget the 'www'!

PHP Session data not being saved

I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?
Here is an example script that does not work on my hosts' server as of right now:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
echo '<p>Refresh</p>';
?>
The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.
Here is the phpinfo() for my hosts' server (PHP Version 4.4.7):
Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH'); in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.
Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions.
Had same problem - what happened to me is our server admin changed the session.cookie_secure boolean to On, which means that cookies will only be sent over a secure connection. Since the cookie was not being found, php was creating a new session every time, thus session variables were not being seen.
Use phpinfo() and check the session.* settings.
Maybe the information is stored in cookies and your browser does not accept cookies, something like that.
Check that first and come back with the results.
You can also do a print_r($_SESSION); to have a dump of this variable and see the content....
Regarding your phpinfo(), is the session.save_path a valid one? Does your web server have write access to this directory?
Hope this helps.
I had following problem
index.php
<?
session_start();
$_SESSION['a'] = 123;
header('location:index2.php');
?>
index2.php
<?
session_start();
echo $_SESSION['a'];
?>
The variable $_SESSION['a'] was not set correctly. Then I have changed the index.php acordingly
<?
session_start();
$_SESSION['a'] = 123;
session_write_close();
header('location:index2.php');
?>
I dont know what this internally means, I just explain it to myself that the session variable change was not quick enough :)
Check to see if the session save path is writable by the web server.
Make sure you have cookies turned on.. (I forget when I turn them off to test something)
Use firefox with the firebug extension to see if the cookie is being set and transmitted back.
And on a unrelated note, start looking at php5, because php 4.4.9 is the last of the php4 series.
Check who the group and owner are of the folder where the script runs. If the group id or user id are wrong, for example, set to root, it will cause sessions to not be saved properly.
Check the value of "views" when before you increment it. If, for some bizarre reason, it's getting set to a string, then when you add 1 to it, it'll always return 1.
if (isset($_SESSION['views'])) {
if (!is_numeric($_SESSION['views'])) {
echo "CRAP!";
}
++$_SESSION['views'];
} else {
$_SESSION['views'] = 1;
}
Well, we can eliminate code error because I tested the code on my own server (PHP 5).
Here's what to check for:
Are you calling session_unset() or session_destroy() anywhere? These functions will delete the session data immediately. If I put these at the end of my script, it begins behaving exactly like you describe.
Does it act the same in all browsers? If it works on one browser and not another, you may have a configuration problem on the nonfunctioning browser (i.e. you turned off cookies and forgot to turn them on, or are blocking cookies by mistake).
Is the session folder writable? You can't test this with is_writable(), so you'll need to go to the folder (from phpinfo() it looks like /var/php_sessions) and make sure sessions are actually getting created.
If you set a session in php5, then try to read it on a php4 page, it might not look in the correct place! Make the pages the same php version or set the session_path.
I spent ages looking for the answer for a similar problem. It wasn't an issue with the code or the setup, as a very similar code worked perfectly in another .php on the same server. Turned out the problem was caused by a very large amount of data being saved into the session in this page. In one place we had a line like this:$_SESSION['full_list'] = $full_list where $full_list was an array of data loaded from the database; each row was an array of about 150 elements. When the code was initially written a couple of years ago, the DB only contained about 1000 rows, so the $full_list contained about 100 elements, each being an array of about 20 elements. With time, the 20 elements turned into 150 and 1000 rows turned into 17000, so the code was storing close to 64 meg of data into the session. Apparently, with this amount of data being stored, it refused to store anything else. Once we changed the code to deal with data locally without saving it into the session, everything worked perfectly.
I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.
Thanks for this one Darryl. This helped me out. I was deleting a session variable, and for some reason it was keeping the session from committing. now i'm just setting it to null instead (which is fine for my app), and it works.
I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.
Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.
Just wanted to add a little note that this can also occur if you accidentally miss the session_start() statement on your pages.
Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out
I had session cookie path set to "//" instead of "/". Firebug is awesome.
Hope it helps somebody.
I had this problem when using secure pages where I was coming from www.domain.com/auth.php that redirected to domain.com/destpage.php. I removed the www from the auth.php link and it worked. This threw me because everything worked otherwise; the session was not set when I arrived at the destination though.
A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.
I've had this issue before where I had a blank line before session_start() which caused it not to work properly.
Adding my solution:
Check if you access the correct domain. I was using www.mysite.com to start the session, and tried to receive it from mysite.com (without the www).
I have solved this by adding a htaccess rewrite of all domains to www to be on the safe side/site.
Also check if you use http or https.
Edit your php.ini.
I think the value of session.gc_probability is 1, so set it to 0.
session.gc_probability=0
Another few things I had to do (I had same problem: no sesson retention after PHP upgrade to 5.4). You many not need these, depending on what your server's php.ini contains (check phpinfio());
session.use_trans_sid=0 ; Do not add session id to URI (osc does this)
session.use_cookies=0; ; ensure cookies are not used
session.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT
session.save_path=~/tmp/osc; ; Set to same as admin setting
session.auto_start = off; Tell PHP not to start sessions, osc code will do this
Basically, your php.ini should be set to no cookies, and session parameters must be consistent with what osc wants.
You may also need to change a few session code snippets in application_top.php - creating objects where none exist in the tep_session_is_registered(...) calls (e eg. navigation object), set $HTTP_ variables to the newer $_SERVER ones and a few other isset tests for empty objects (google for info). I ended up being able to use the original sessions.php files (includes/classes and includes/functions) with a slightly modified application_top.php to get things going again. The php.ini settings were the main problem, but this of course depends on what your server company has installed as the defaults.

Categories