Session 5 Recap: Cookies, Sessions
A summary of some of the main points about cookies and sessions:
- HTTP is stateless. Each http request/response transaction is an isolated event with no context.
- Cookies are pieces of data that a server can send to a client via the Set-Cookie header. If the client accepts the cookie, the client
sends back the same cookie as part of the request header on subsequent requests. This provides a means for the application on the server side to identify
and track clients, and simulate state.
- In PHP sessions, client-specific data is stored on the server side and persists across multiple HTTP requests.
- You begin a session, or resume an existing one, by calling session_start().
You have to call session_start() on every page that you want to be session-aware, and do it before you try to read/write $_SESSION
- Thereafter, you can get and set session variables via the $_SESSION array.
- Cookies are often used for passing a session id back and forth so that the application on the server side can know which client it is talking to.
(In fact, in PHP's default file-based session management, there is a like-named file from which PHP reads and to which PHP writes the $_SESSION data at
the start/end of each request.)
- You can have cookies without sessions. Cookies in and of themselves do not a session make.
- You can have sessions without cookies, if you propagate the session id from one request to the next by some other means, such as appending the session id to every URL as part of the query string, e.g., page.php?PHPSESSID=e4c6a1142acf69a9b65e15cbbf30e731.
This technique, however, is more susceptible than cookies to accidentally divulging the session id and
compromising security.
- PHP can automatically rewrite URLs (in the above manner) if you enable session.use_trans_id.
- PHP can be configured to use cookies exclusively, use URL-rewriting exclusively, or use URL-rewriting conditionally,
i.e., if and only if the client declines the cookie. The relevant config settings are session.use_cookies, session.use_only_cookies, session.use_trans_sid.
- Cookies are the most common — and some argue, the most desireable — means of propagating the session id across requests.
Please feel free if you have any questions.
[week 5 examples] [main page] [lecture notes] | Last update 2012-03-20 8:05 am