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.
If you are using
session_set_cookie_params()
you might want to check if you are passing the fourth param$secure
astrue
. 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 toFALSE
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 thehttpd-ssl.conf
of the server so that your local url is served https.After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.
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.
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 thephp.ini
file.So, if someone reads this, please check
php.ini
config before anything else.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'!
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.