Search code examples
phpsessionsession-variables

PHP Sessions Troubleshooting


There's a lot of questions on here about PHP sessions, but none of the solutions seem to be working for me. I made a test script to showcase the issue:

session1.php

session_start();

$_SESSION['user'] = 'Test';

header('location: session2.php');
exit;
?>

session2.php

session_start();

print_r($_SESSION);

?>

This is a very simple example, however I'm using sessions in my site to rely on if a user is logged in or not. It worked for a while, then I had to reinstall my server and it just stopped working. For reference, this is the question that I used which had a lot of possible solutions in it: Session variables not working php

Here's what I've tried so far

  • Put exit; after the header redirect
  • Redirect to the same domain, I've tried putting the entire url in the redirect as well but it was not successful. Besides, it should do this automatically if you're just putting in a file name (from my experience)
  • Setting the session.save_path to "/var/lib/php/session" in php.ini
  • Ensuring full read/write access for the script owner (root), also making sure root is the owner ls -ld /var/lib/php/session returns

drwxrwxrwx. 2 root apache 4096 Apr 9 16:55 /var/lib/php/session

  • Setting session.cookie_lifetime to 3600, shouldn't be necessary but I can just try
  • Changing session.cookie_domain to my domain, again, it shouldn't be necessary since it does this properly by default

None of this worked for me so far. I hope I'm overlooking something simple.

As you can see, the $_SESSION is entirely empty in session2.php. Btw, I have rebooted apache after making changes to php.ini :)


Solution

  • Okay, I've figured it out! Thanks everyone for your suggestions, turns out I need to learn to read error logs ...

    I use vestacp and apparently it defaults the PHP sessions to /home/admin/tmp, and I'm not sure how but you're not able to change that (which I did). There was another problem though, the ownership and permissions weren't correct for that folder. Turns out all I needed was a chmod -R 700 /home/admin/tmp and chown -R root /home/admin/tmp - which I already tried on the other folder but it didn't allow that.

    Btw, here's the error line that triggered the 'oh what the hell I can't change the session directory':

    Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/home/admin/tmp) in Unknown on line 0