Background: PHP Sessions

State Representation in HTTP


HTTP, the protocol over which the web is built, is a stateless protocol. Each HTTP request is user session context independent, and the server is, on the HTTP protocol level, unaware of any relationship between consecutive requests.
This has made HTTP a highly scalable and versatile protocol. However, in most Web applications some notion of a user session – that is short-term, user specific data storage, is required.
For example, without some sort of state representation a web application cannot distinguish between logged-in users (or technically put, requests coming from an HTTP client that has logged in) and non logged-in users. In many cases even more complex data, such as the contents of a shopping cart, must be maintained between requests and attached to a specific user or browser.
HTTP leaves the solution of such problems to the application. In the PHP world, as in most web-oriented platforms, two main standard methods exist for storing short-term user specific data: Cookies and Sessions.
HTTP Cookies
Cookies are set by the server, and are stored by the browser on the end user’s machine. Browsers will re-send a Cookie to the same domain in which it originated, until it expires. This allows storing limited amounts of user-specific information and making them available to the application on each request made by the same user. Cookies are convenient and scalable (no storage is required on the server side), but are also limited due to a number of reasons:
Cookies are limited in size, and the limit varies per browser. Even if the limit is high, large amounts of data sent back and forth in each request may have a negative effect on performance and bandwidth consumption.
Cookies are sent repeatedly, on each request to the server. This means that any sensitive data contained in cookies is exposed to sniffing attacks, unless HTTPS is constantly used – which is in most cases not an effective option.
Cookies store strings – storing other, more complex types of information will require serialization and de-serialization to be handled in the application level.
Cookie data is stored on the client side – and as such, is exposed to manipulation and forgery by end users, and cannot be trusted by the server.

These limitations make it almost impossible to rely on Cookies to solve all state representation problems. As a better solution, PHP offers the Sessions concept.

0 comments: