By using this site you agree to the use of cookies.

Learn more

Share via:

Sessions in PHP

Tutorial showing how to use Sessions in PHP.

Edited: 2017-03-16 23:33

PHP article image

Sessions are useful to store information temporarily. An example would be a users logged-in state to lift the burden from the server, while checks would still be made at kay parts, such when submitting a form.

How they Work

sessions are like variables, they work by using "session_start()" before declaring any of the session variables.



$_SESSION['UserName'] = 'Jacob';

<a href="NextPage.php">Next Page</a>

The above will make php remember the name "Jacob", in a session variable, usually linked with the user by a cookie storing the unique session id.

Session ID's in URL's

Its also possible to store this ID in the URL, so that the user dosn't need to have cookies anabled.

<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 include the session id in the urls, but this is generally bad.

As far as i'm concerned, its the users own responsibility to add your site to their trusted lists, if they have disabled cookies.

Finalley the Content of NextPage.php



echo '<p>' . $_SESSION['UserName'] . '</p>';

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

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(), see below.

  setcookie ("PHPSESSID", "", time()-60*60*24*100); // make the browser delete the cookie

You may want to use "session_regenerate_id()" to generate a new id, instead of clearing the cookie intirely.