Thursday, November 12, 2009

AJAX and PHP sessions

One thing that trips up AJAX development is how to persist your PHP session through your AJAX calls. In a browser, the session persists through a cookie that passes the session id upon each request. However with an AJAX call, the browser cookies are not passed and the session is lost.

There are a couple of easy ways around this. First, if your AJAX library supports cookies, you can just set the PHP session id cookie before the call. If you don't have cookie support, then the following "manual" method works quite well.

What you will want to do is pass the session id as a POST or GET variable in your AJAX request. We'll call our variable name "sid".

Here is a jQuery example for passing the sid through as a POST value (in a PHP script):

$.post("test.php", { sid: "<?php echo session_id(); ?>" } );

This will POST the current session id through the form. Next on the PHP side, you must set the session id with this posted value:


<?php
// set session to value from ajax post
session_id($_POST['sid']);
// we now have $_SESSION data!
?>

As for security, be aware that you don't have the same restrictions that come with cookies (domain, date, etc.) so once you pass the session id to javascript, be careful what can be manipulated through javascript code. It's pretty much the same as being aware of javascript getting/setting cookie values themselves.

Hope that helps!