Loosing PHP Session Variables

Loosing Session Variables (PHP $_SESSION)

PHP $_SESSION is a PHP “super-global” that can store variables across multiple PHP pages/scripts making it a perfect choice for writing “members area” code for example. However, the topic of the post is not about what you can do with the PHP session, but what can you do when it doesn’t work (you are loosing the session variables across pages). See below a few possible situations:

What to check and how to fix it

  1. Session Initialization. – Check to make sure that your session initialization session_start() appears on the top of every page where session variables are needed. On the top doesn’t necessarily means first thing after the < php? tag, but make sure it appears before any HTML output and before actually using the session variables in whatever data processing you're doing.
  2. Session Closing. – How are you moving from page to page? Are you redirecting the user in the middle of a script? I’m asking this because when a script ends or die()s, the session is automagically closed and data saved. If a redirect is in place the script might not have a chance to die naturally so the session data is not saved. Fix? Make sure the data is saved before doing the redirect by calling session_write_close() .
  3. php.ini Configuration. – It’s a less common situation but it drove me crazy for about one hour before figuring it out. If you modify stuff in your php.ini make sure you know what you’re doing. Before learning about PHP sessions I was fooling around and in the [Session] section of the php.ini file and I un-commented this line: ;session.save_path = “/tmp” (took the ; away). No harm done, right? The session will be saved in the /tmp folder, right? Wrong! The session no longer worked (I was loosing session variables when changing pages). So, check your php.ini file …

Post a Comment

Your email is never published nor shared. Required fields are marked *

CAPTCHA image