Wednesday, May 7, 2014

What are sessions? How do they work?

In many dynamic web sites you want to store user data between HTTP requests (because http is stateless and you can't otherwise associate a request to any other request), but you don't want that data to be maintained client side (in the cookie, in URL parameters (like http://example.com/myPage?asd=lol&boo=no), and so on...) because you don't want the client to play around with that data without passing through your (server side) code.
The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented.
Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.
In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

No comments:

Post a Comment