Reputation: 17001
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).
Upvotes: 174
Views: 275724
Reputation: 17001
First, carry out these usual checks:
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.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();
)$_SESSION
superglobal array is not overwritten anywherewww.yourdomain.com
to yourdomain.com
doesn't carry the session forward..php
(it happens!)PHPSESSID
cookie value that is returned by the server, and one sent by the browser when requesting another file. In case they differ, it's a problem with cookies. In case they are the same, it's a problem with session storageNow, 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)
Upvotes: 256
Reputation: 2307
Sometimes the issue involves the PHP INI session settings such as session.cookie_samesite
not being set, or not being set to match your use case. Most cookie/session/security related errors appear in the developer console/network log of web browsers (F12 key in Windows), but keep in mind that each web browser handles things differently.
I had a site that kept dropping the user session in Microsoft Edge browser but not Firefox. The network log in Edge said my session SameSite
setting was not set, which I didn't think was a problem until I added ini_set("session.cookie_samesite", "None");
to my application. Making that change fixed my issue of Edge dropping my user session. So if your session issues appear in one browser vs another, check the browser network logs for differences in security errors.
Upvotes: 0
Reputation: 51
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');
Upvotes: 1
Reputation: 10922
My problem was slightly different than the others.
I am trying to implement Google oAuth on my website.
My website's dev url is website.local
, the Google redirecting url was 127.0.0.1
.
As they're not the same domain, two different session_ids were created.
Upvotes: 0
Reputation: 107
KEY POINT'S
Upvotes: 2
Reputation: 4392
Here's my 2 cents on this problem as I don't see anyone mentioned this case..
If your application is functioning thru a load balancer on a multiple nodes you can't save session into files or need to share this path for all nodes otherwise each node will have its own session files and you will run into inconsistency.
So I'm refactoring my app to use database instead of file system.
Upvotes: 0
Reputation: 5406
OP didn't specify if he's redirecting to the same page (for example after login) if so server/browser caching could also be the problem
A simple workaround would be to append version number at the end of the URL (like you would when forcing .CSS file refresh)
Example:
header('Location: index.php?v='.time());
So the user is redirected to which is treated like a new page
domain.com/index.php?v=122234982323
Upvotes: 0
Reputation: 3471
Quick and working solution for me, was just simply double redirect. I created 2 files: fb-go.php
and fb-redirect.php
Where fb-go.php
looked like:
session_start();
$_SESSION['FBRLH_state'] = 'some_unique_string_for_each_call';
header('Location: fb-redirect.php');
and fb-redirect:
session_start();
header('Location: FULL_facebook_url_with_' . $_SESSION['FBRLH_state'] . '_value');
Also worth to mention is Android Chrome browser behavior. Where user can see something like that:
If user will chose Facebook app, then session is lost, because of opening in Facebook browser - not Chrome, which is storing user session data.
Upvotes: 0
Reputation: 51
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")
Upvotes: 5
Reputation: 698
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.
Upvotes: 1
Reputation: 3274
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
Too late to reply but this worked for me
Upvotes: 1
Reputation: 1
Today I had this problem in a project and I had to change this parameter to false (or remove the lines, by default is disabled):
ini_set( 'session.cookie_secure', 1 );
This happened because the actual project works over http and not https only. Found more info in the docs http://php.net/manual/en/session.security.ini.php
Upvotes: 0
Reputation: 119
Make sure a new session is created properly by first destroying the old session.
session_start();
session_unset(); // remove all session variables
session_destroy(); // destroy the session
session_start();
$_SESSION['username'] = 'username';
Yes, session_start()
is called twice. Once to call the unset and destroy commands and a second time to start a fresh session.
Upvotes: -5
Reputation: 1963
I fixed by giving group write permissions to the path where PHP store session files. You can find session path with session_save_path() function.
Upvotes: 0
Reputation: 41
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'!
Upvotes: 0
Reputation: 5844
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.
Upvotes: 0
Reputation: 1
session_start();
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
if(!isset($_SESSION['name_session'])){
unset($_SESSION['name_session']);
session_destroy();
}
if(isset($_SESSION['name_session'])){
$username = $_SESSION['name_session'];
}
Upvotes: -2
Reputation: 34
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;
Upvotes: 0
Reputation: 455
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
Upvotes: 1
Reputation: 21
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.
Upvotes: 1
Reputation: 2587
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())
Upvotes: 0
Reputation: 704
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.
Upvotes: 2
Reputation: 207
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.
Upvotes: 8
Reputation: 1403
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!!!
Upvotes: 2
Reputation: 51
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.
Upvotes: 3
Reputation: 3405
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');
Upvotes: 0
Reputation: 349
you should use "exit" after header-call
header('Location: http://www.example.com/?blabla=blubb');
exit;
Upvotes: 29
Reputation: 4617
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]
Upvotes: 0
Reputation: 195
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.
Upvotes: 13
Reputation: 2183
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.
Upvotes: 0