PHP Sessions tricks

Here are some tips & tricks we use for PHP sessions:

Release session file using with session_write_close ...

Don't wait till the script finishes. "You all know" that when opening a session, the session file is blocked by the PHP process till the scripts releases it. So if you have a site with a lot of concurrent ajax calls that open session (logged in users?), those calls will be waiting till the session is released (so you are serializing your ajax calls in the server).

One way to prevent this is to release the session after writing to it. To do this, just have to call:
after manipulating the session. You will have the session available in $_SESSION but read only. Whenever you want to write something in the session, just call:

Use memcached to store sessions if available ...

There are a lot of benefits in this approach:

  • easy to install / deploy.
  • shared sessions between servers.
  • super fast (works in memory).
  • very easy to scale (just add more memcached servers!)

The only drawback i see in with this approach is that you dont have persistent session storage, so if you reboot memcached say bye bye to your sessions.


First install memcached, there are packages for almost any linux distribution, on debian / ubuntu:
~ apt-get install memcached
It will be available by default in localhost port  11211
Then install  the PHP extension:
~ apt-get install php5-memcache
 Finally change your PHP (/etc/php5/apache2/php.ini) setting
session.save_handler = files 
session.save_handler = memcache
Done! restart apache and you are ready to go!.


Use Database session handler 

This is approach is widely used, and its main benefits are:

  • shared sessions between servers.
  • persistent storage.

From the manual:
To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions. As of PHP 5.4.0 you may create session handlers using the SessionHandlerInterface or extend internal PHP handlers by inheriting from SessionHandler.
The process basically is:
  • create a table called sessions
  • create a class called for example: "MySessionHandler" implementing SessionHandlerInterface.
  • register that class as the default error handler: 

Or you can use the Session Save Handlers from Zend Framework 2 that makes you life a lot easier.


No hay comentarios.:

Publicar un comentario