Sunday, November 16, 2008

PHP Session Manipulation

Today on linuxquestion somebody asked something about PHP's session variable. Which I thought was quite interesting. The question goes: "Can we actually manipulate the PHP session information on the server? If so how?"

Well this question actually brings two more questions in my mind instantly:
1.) Is PHP session information stored only on the server?
We can't actually manipulate PHP information that resides on the server, it is just not really possible security wise. But what we can do is manipulate it in such a way that we can resume it even after it dies when garbage collector destroys it.

2.) How is PHP Session stored on the server? On disk or in memory?
The first time you call session_start(), PHP basically generates a new session ID and creates an empty file to store session variables. PHP also sends a cookie back to the client that contains the session ID.

There are a couple of techniques to session resumption.
1.) Cookies - Store session information into cookie as it is being stored on the session variable. That way, when we resume our session after we close the browser window, we can first of all check if there was a cookie set, and if there is, read that cookie information to the session and start.

2.) Database - Store session information into database as it is being stored on the session variable. Similar to the cookie approach, but this is preferred because it is really permanent and it does not rely on the client's cookie function (some client disable cookies on their browser).

3.) Mixture of Cookies + Database. Cookies is faster than database but database is more persistent than a cookie. Therefore, a mixture of this techniques allows for a persistent and fast session resumption.

No comments: