PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

PHP Session Debugging

Note: This article was originally published at Planet PHP on 26 March 2011.
Planet PHP

For many PHP developers, calling session_start() and using $_SESSION for stuff you want to persist from page to page is all there is to know about sessions. This is understandable, because PHP's native session support is so simple and reliable. But, what if something goes wrong?

Understanding how sessions work is your best tool when it's time to debug a problem. There's really no substitute. I wrote The Truth about Sessions way back in 2003, and it focuses on an outdated technique, but I think it's still worth reading to learn a bit more about how sessions work. (Just read the first few sections.)

Nothing beats getting your hands dirty, and session_set_save_handler() can help. If you're not already using this function, the manual has an example that mimics the native behavior. Storing Sessions in a Database, another old article, shows you how to store sessions in MySQL. For now, it's just important that you're using a custom session handler, because this gives you more insight into what's really going on.

If you're having trouble getting session_set_save_handler() working, don't worry. Figuring out what's wrong is a valuable learning exercise. If you're using the example from the manual, note that it depends upon configuration directives like session.save_path being set correctly.

When something goes wrong, it's almost impossible to determine the exact cause of the problem without some record of what happened. Was the session identifier sent in the request? Was it the same one that was sent in the previous request? Was the session data saved properly? I could come up with dozens of questions like these, because there are a lot of things that can fail, but the point is that we need answers.

Let's look at the read() function from the example in the manual:

A function read($id) { global $sess_save_path; A $sess_file = "$sess_save_path/sess_$id"; return (string) @file_get_contents($sess_file); } A ?

There are a few questions that can be asked:

  • What is the value of $id?
  • Are we able to read from $sess_file?
  • What data is returned?

With a few modifications, you can answer these questions:

A function read($id) { global $sess_save_path; A echo "

Session identifier is: {$id}

"; A $sess_file = "{$sess_save_path}/sess_{$id}""/

Truncated by Planet PHP, read more at the original (another 6866 bytes)