News & UpdatesProgrammingWeb programmingPartnersStore
Book Cover
Buy Now
Projects
Links

PHP Tutorial – 16 – Sessions

Sessions provide a way to make data accessible throughout a website.

Starting a session

To begin a session the session_start function is used. This function must appear before the any output is sent to the client.

session_start();

Session array

With the session started the $_SESSION array can now be used to store data. As an example, the page view count for the duration of a session can be stored with the code below. The first time the page is viewed the element will be initialized to its default value of zero.

$_SESSION['views'] = $_SESSION['views'] + 1;

This element can now be retrieved from any page on the domain as long as session_start is called on the top of that page. If the user already has an ongoing session this function will resume that session.

echo "Count: ". $_SESSION['views'];

Session duration

A session is only guaranteed to last until the user leaves the website. Then the garbage collector is free to delete that session. To manually remove an element the unset function can be used and for removing all session variables there’s the session_destroy function.

unset($_SESSION['count']); // destroy variable
session_destroy();         // destroy session

If you like this tutorial please +1 it:


Leave a Reply