PhpRiot
Follow phpriot on Twitter
Sponsored Link
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Storing encrypted session information in a cookie

Note: This article was originally published at Planet PHP on 13 July 2010.
Planet PHP

Our session system is due for an upgrade. Currently all PHP sessions are stored in the database, and some things are getting a bit slow. There have been a couple of approaches I've been considering, one of which is simply storing all the information in a browser cookie.

First I want to make clear I don't necessarily condone this. The reason I'm writing this post, is because I'm hoping for some more community feedback. Is this a really bad idea? I would love to know.

The benefits

If all the session data is stored in the browser, it means that I don't need to store it on the server. I actually don't care all that much for having the data on the server (unless it's the only secure way), it's mostly a gigantic map with session tokens and user id's (along with some other info).

I also feel it's more natural for HTTP, as it makes it a bit more stateless.

Sample code

  1. class BrowserSession {
  2. A  A  public $secret = 'this will need to be a cryptographic random number';
  3. A  A  public $currentUser = null;
  4. A  A  // Sessions time out after 10 minutes
  5. A  A  public $timeout = 600;
  6. A  A  function init() {
  7. A  A  A  A  if (!isset($_COOKIE['MYSESSION'])) {
  8. A  A  A  A  A  A  echo "No session cookie found\n";
  9. A  A  A  A  A  A  return;
  10. A  A  A  A  }
  11. A  A  A  A  list($userId, $time, $signature) = explode(':',$_COOKIE['MYSESSION']);
  12. A  A  A  A 
  13. A  A  A  A  // The cookie is old
  14. A  A  A  A  if ($time time() + $this-timeout) {
  15. A  A  A  A  A  A  echo "The session cookie timed out\n"

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