tags:

views:

242

answers:

3

I am interested in knowing how session management and cookies work in PHP. I want to know their underlying mechanism, like how the browser interacts with the cookies, and how the cookies are used to validate the session data in the server.

Is there any web resources that allow me to learn that?

+1  A: 

From PHP’s Session Handling manual:

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

This unique id is a big random number that is stored on the server side to match it next time the client makes a new request. It typically goes into the /tmp directory.

kmkaplan
+2  A: 

In PHP in particular, the standard way sessions work is that PHP generates a random session ID, and puts it in a cookie. (By default called PHPSESSID) This cookie is handled by the browser by saving it locally on the user's machine, and is sent with every request to the domain it belongs to.

This session ID is then used to refer to a data store on the server machine, by standard located in /tmp/ on an apache install on linux. This is where everything in the $_SESSION array is stored between requests.

As you may notice, this is only as safe as the cookie is, as there is no real authentication between the user and server that the user is the "real" owner of the session ID. This means that so-called "session hijacking" is possible by sniffing the cookie and inserting the cookie with the session ID on the attacker's machine. This can be used to take over an account on a webpage, and browse around it just as if you were the original user, because to the server you are.

There's also an alternate, even more unsafe, way of keeping the session alive that PHP supports. This is done by sending the session ID as a GET variable with every link. As you may notice, this means that if a user simply copy-pastes one of these links, he will be giving away all his credentials. =)

Further information could be found in the PHP manual.

Daniel Bruce
A: 

A cookie is a bit of data that's associated with a HTTP address. I.e.

1/ Browser requests www.google.com
2/ www.google.com response includes setting a cookie
3/ From this point on and as long as the cookie is valid (there's an expiry time associated with it), each subsequent request made by the browser to www.google.com/anything includes the cookie above

For details: http://en.wikipedia.org/wiki/HTTP_cookie

A cookie permits creating a session in the otherwise stateless HTTP protocol in the sense that it allows a client-server conversation to be isolated from other clients interacting with the server.

diciu