Press "Enter" to skip to content

PHP – load session by a given session ID

Last week I have bumped into a small problem that caused me a few hours head ache… I had a desktop application written in Adobe AIR and a server offering web services in PHP. The users of the desktop application could log in and their session variables had to be stored on the server. The only data the desktop application stored was the session ID returned by the web service after logging in.

After logging in, the desktop application made it possible to make some changes on the DB behind the server by using the web services. To identify the user, it passed the session ID to the server…

Getting the session ID is not a big deal in PHP, one can use the session_id() function after starting a new session. The tricky part was to load the session with the ID passed as parameter. Actually it wasn’t that tricky, I just didn’t get any useful information on the web. I read some freaky suggestions, like storing the sessions in a hash map or implementing my own session handler…

Fortunately the solution is a lot easier than any of the suggestions. One may get a session by an ID in PHP by setting the session ID before calling the session_start() method using the session_id($sid) function:


After this, if you call the session_id() function, it will return the same ID as $sid, so you have successfully loaded the required session.