Ajax Requests and PHP Sessions Solution

Aug 29
18:04

2006

Pedro Rubini

Pedro Rubini

  • Share this article on Facebook
  • Share this article on Twitter
  • Share this article on Linkedin

With the popularity of AJAX and Web 2.0, I must certainly not be the first, or last person whatsoever, who has got troubles handling PHP Sessions and Ajax at once. When I google "ajax php sessions" what I run into are massive forum threads that don't provide me with a solution at all, or rather just give me tips that lead me to endless research. Anyways, to spare other people from being through the same experience, I'm writing a short article with a "temporary solution" for the matter.

mediaimage

Ajaxian Thread "Trouble with Asynchronous Ajax Requests and PHP Sessions",Ajax Requests and PHP Sessions Solution Articles community member Andy, says:

"Concurrency issues have long since been solved, if you actually use the recommended methods of avoiding them. Any modern book on threading will give you the basics. With PHP it is especially problematic because each session “variable” is just an array index, and the entire session gets read or written at once, you can not access (or lock) just a single session “variable”. But this is hardly a PHP only or AJAX only problem. You would have the same kinds of issues with any series of multiple concurrent requests for the same page (like downloading images on the page that are dynamically generated based on session data).

The main issue here is that there are no built-in concurrency controls across multiple requests in popular server-side programming/scripting languages, so you’d have to roll your own. Things like atomic increment in memcached or get_lock/release_lock in mysql can help. One may have to forgo using PHP’s session handling to get finer grained locks, which means rolling your own session variable storage engine also.

"where I realize "rolling my own session variable storage engine" is exactly what I need. I looked up for a MySQL session storage engine to replace php default sessions handling system, since I was too lazy to code one myself, and I found a class at phpclasses.org called "MySQL Session" that serves the purpose.

I've tested the class and it works perfectly fine, thanks to the french coder Julien Pachet. I hope more people will find this useful.