PHP
PHP introduction
PHP basics
PHP variables
PHP functions
PHP conditions
PHP loops
PHP arrays
PHP OOP
PHP strings
PHP forms
PHP entitites
PHP files
PHP include files
PHP date and time
PHP cookies
PHP databases
PHP sessions
PHP summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Browser scripting

Javascript
VBScript
AJAX

Server scripting

ASP

Making money online

Make money online

PHP sessions

What if you could make changes or store information about what happens during a users visit to a website? You can with PHP sessions.

This lesson focuses on:

What is a session?

A session is the time a user spends at a website encompassing everything they do in that time at the website. PHP allows for what is called a session variable - a variable that is used to store information about, or change settings for a users session. A session variable can hold information about a single user, and is available to all pages within the same domain.

NOTE: Session information is temporary, it will be deleted once the user leaves a website. For permanent storage, databases can be used.

Starting a session

The way sessions work is by assigning a unique ID for each visitor and storing data based on this ID. This ID is either stored in a cookie or is part of the URL.

Before being able to store information, you have to start a session. This is accomplished with the session_start() function.

NOTE: The session_start() function must be the first thing in your code, even before the <!DOCTYPE> declaration!

Example:

<?php
session_start();
?>
<html>
<body>
</body>
</html>

The above example will start a new session, allow you to save information, and assign an ID to the user.

Storing and using session variables

You can store and use session variables through the $_SESSION associative array.

Example:

<?php
$_SESSION['views'] = $_SESSION['views'] + 1;
?>
<html>
<body>
</body>
</html>

In the above example, the 'views' index of the $_SESSION associative array is incremented by 1 every time a webpage is visited.

Destroying a session

Sessions are destroyed through the use of the session_destroy() function. Using session_destroy() will result in the loss of all data stored in the session. Alternatively, you can use the unset() function which will destroy only some of the data in the session, as opposed to the entire session.

Example of destroying only some data in a session:

<?php
unset($_SESSION['views']);
?>

Example od destroying an entire session:

<?php
session_destroy();
?>

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments