Membership
Main Menu
Forum Boards
Stats
- 18 tutorials
- 72,337 members
- 696,731 forum posts
- 11 blog posts
Tutorials
Sessions and cookies: Adding state to a stateless protocol
Views: 21147
Sessions
Another popular method is using sessions. Sessions are very similar to cookies, but they are distinctive in a few important ways. While cookies are stored on the client machine, sessions are stored on the server.
The way sessions work are by generating a random ID for the user. This ID is stored in a cookie on the client machine. PHP will then fetch all session data related to that ID from wherever it is stored. By default it's stored on the harddisk, but it's possible to write your own save handler so you can store it in e.g. a database. By default, the cookie will be called PHPSESSID and will expire when the browser is closed.
Seeing as you are using a cookie for identifying the user you'll need a way to set the same settings for the cookie as we did before. For this purpose you can use the session_set_cookie_params() function. It has the following syntax:
session_set_cookie_params(int $lifetime[, string $path[, string $domain[, bool $secure[, bool $httponly]]]])
Using session data
Before you are able to use sessions you'll have to call session_start(). This function will, like when setting cookies, have to be called before any output has been sent to the browser. Once this has been done, storing data in sessions and retrieving the values is quite easy:
Like $_COOKIE, $_SESSION is a super-global as well.
An example of using sessions
This is how the script we made using cookies on the previous page will look if we decide to use sessions instead:
Sessions without cookies
Sessions do not always have to use cookies. Whatever value you choose for the session name (PHPSESSID by default) just have to be present somewhere. It could for instance be through the URL like this: http://example.com/index.php?PHPSESSID=jfJk87Hfja87Hajhsd97Hash or it could be through a form field (either via POST or GET). The manual has more information about this, but I would recommend you just use the cookies.
On the next page we will talk a bit about security...
