PHP: Sessions

In PHP, Sessions are a useful way to store information temporarily. An example would be whether a user is logged-in or not.

PHP has build-in functions to manage sessions, which allow you to create login systems, and other fancy functions for your web applications.

How they Work

Sessions can be thought of as "variables". The values you store can be anything from e-mail addresses, login details (a hashed password, and a username). The values are accessible via the $_SESSION array, and are stored on the server-side, usually linked via a cookie on the users device. To create a session in PHP, you must first use session_start() before declaring any of the session values.

Simply link normally from one page to the next, PHP automatically retrieves the session id in the cookie called "PHPSESSID".

Session IDs in URLs

It is also possible to store the session ID in the URL. Doing this will make the session work, even for people who have disabled cookies in their browser.

<a href="NextPage.php?<?php echo SID; ?>">Next Page</a>

There are two ways to link the session to the user. Either you need to use cookies, or you need to include the session id in the URLs. In general, it is recommended not to have session IDs in the URL, since it could cause problems when users are copying the URLs, and if search engines happen to index URLs containing session IDs.

Note. For people who have disabled cookies, it can be argued that it is their own responsibility to add your site to their trusted list in their browser. Cookies are dangerous, as often claimed in the media.

Destroying a Session

To destroy a session, or log the user out, session_destroy() may be used. However, you also need to clear the cookie with cookie(), like done below: