27

Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.

<?php
session_start();

include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database    

if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
    header("Location:http://xyz/inbox.php?u=$id_user_fetched");
    //echo 'Login Successful';
    }else{
        echo 'Invalid Login';
        echo'<br /> <a href="index.html">Click here to try again</a>';
        }
}else{
    echo mysqli_error("Login Credentials Incorrect!");
    }
?>

The inbox.php page looks like this:

<?php
session_start(); 
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
 //REST OF THE CODE

?>

Now with the above code, the inbox.php always shows the output: SESSION=you must log in to see this page. Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?

Arihant
  • 3,847
  • 16
  • 55
  • 86

12 Answers12

51
  1. 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 tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
  2. 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();).
  3. Make sure cookies are enabled in the browser you are using to test it on.
  4. 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.
  5. Make sure you didn't delete or empty the session.
  6. Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
  7. Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
  8. Make sure your file extension is .php (it happens!).

PHP session lost after redirect

Community
  • 1
  • 1
revo
  • 47,783
  • 14
  • 74
  • 117
  • could it possibly be a server error? i tried the most basic test examples as under: session.php session2.php: – Arihant Oct 30 '13 at 20:13
  • 2
    I have same problem. Cause: there was no free disk space! – Cuarcuiu Nov 30 '15 at 17:12
  • same problem for me. i try to print the page using google cloud print but the session are closed/cleared. how to fix that – Karthi Feb 28 '17 at 12:44
  • Regarding #4: This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. http://php.net/manual/en/security.globals.php – Chiwda Aug 28 '17 at 09:47
  • For me this problem is caused by no disk space, as Cuarculu. I suggest revo to add this cause in his list. Thanks – Tama Oct 04 '18 at 09:00
  • Seems so simple, but adding `exit;` was the solution for me after 30 minutes of (virtually) tearing my hair out. – jcgoble3 Mar 27 '20 at 02:51
  • 2
    #7 was key, being logged in on www and then testing on url without www makes session disappear! – Captain Fantastic May 05 '20 at 14:49
  • The 4th point of register_globals was very helpful. It solved my problem. Thank you. – Darshan Jain Sep 25 '20 at 13:26
12

I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.

Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.

Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.

Vadman
  • 141
  • 2
  • 5
  • 777 is a bad set of permissions for the session save folder. You need to change the ownership of the folder to allow the web server to write to it and prevent all other access. – user2182349 Aug 10 '15 at 12:28
  • 1
    HOOOOLY SHIT man, all the best in your life, I was literally crying because I couldn't get session onto the next page. – Rok Dolinar Mar 31 '16 at 20:09
8

If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.

Community
  • 1
  • 1
  • 1
    Oh! I had one form where I input username and try to use that username on other page. Basically, my mistake was to not call `session_start()` on another page where I retrieve that username. Thanks. That really helped. – Omkar76 Jul 29 '21 at 05:29
3

Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.

Andrey Moiseev
  • 3,914
  • 7
  • 48
  • 64
Ashraf Ali
  • 31
  • 1
2

Just talked to the hosting service, it was an issue at their end. he said " your account session.save_path was not set as a result issue arise. I set it for you now."

And it works fine after that :)

Arihant
  • 3,847
  • 16
  • 55
  • 86
2

Maybe it helps others, myself I had

session_regenerate_id(false);

I removed it and all ok!

after login was ok... ouch!

Oliver M Grech
  • 3,071
  • 1
  • 21
  • 36
1

I had similar issue and with the cookie domain:

    ini_set('session.cookie_domain', '.domain.com');

the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.

talsibony
  • 8,448
  • 6
  • 47
  • 46
1

The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.

session_set_cookie_params(0)
Jacek Dziurdzikowski
  • 2,015
  • 2
  • 13
  • 20
0

I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com

Devqxz
  • 51
  • 1
  • 6
0

I was also facing the same problem i did the following steps to resolve the issue

  1. I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info

2 After that just changed the permission given below *chown root.apache /var/lib/php/session * That's it. These above steps resolve my issue

Aman Shukla
  • 61
  • 1
  • 1
0

Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.

I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.

A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.

echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();

In my case I could fix the issue by casting my username to string as follows:

$_SESSION['Username'] = (string)$userData->Username;

Cost: 1 nights sleep.

AnthonyVO
  • 3,821
  • 1
  • 36
  • 41
0

In my case none of above are working then I use ob_clean at the top and it worked like a charm.

ob_clean();
session_start();
Hadayat Niazi
  • 1,991
  • 3
  • 16
  • 28