[php] 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.

This question is related to php session redirect session-cookies shared-hosting

The answer is


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:

  1. Disk space problem. Make sure your disk space is not full, you need some space to store session files.

  2. Session directory may not be writable. You can check it with is_writable(session_save_path())


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:

Android

If user will chose Facebook app, then session is lost, because of opening in Facebook browser - not Chrome, which is storing user session data.


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.


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!


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'];
    }

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]

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.


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.


you should use "exit" after header-call

header('Location: http://www.example.com/?blabla=blubb');
exit;

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.


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'!


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.


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.


KEY POINT'S

  1. Do not start a session on the return page.
  2. Don't use session variable and not include header.php which user session variable
  3. Just make a link go to home page or profile page after insert payment info and status

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

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.


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.


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'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!


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.


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!!!


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;

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.


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


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


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.


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

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:

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.


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.


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.


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

ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();

Too late to reply but this worked for me


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.


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


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');

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?

Examples related to redirect

React-Router External link Laravel 5.4 redirection to custom url after login How to redirect to another page in node.js How to redirect to an external URL in Angular2? How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Use .htaccess to redirect HTTP to HTTPs How to redirect back to form with input - Laravel 5 Using $window or $location to Redirect in AngularJS yii2 redirect in controller action does not work? Python Requests library redirect new url

Examples related to session-cookies

Invalidating JSON Web Tokens PHP session lost after redirect How to use cURL to send Cookies? Using Python Requests: Sessions, Cookies, and POST What is the difference between server side cookie and client side cookie? Check if cookies are enabled How to delete cookies on an ASP.NET website What is the difference between Sessions and Cookies in PHP? How to secure the ASP.NET_SessionId cookie?

Examples related to shared-hosting

How to access site through IP address when website is on a shared host? PHP session lost after redirect Change primary key column in SQL Server