PHP
  1. PHP intro
  2. PHP basics
  3. PHP variables
  4. PHP functions
  5. PHP conditions
  6. PHP loops
  7. PHP arrays
  8. PHP classes & objects
  9. PHP strings
  10. PHP forms
  11. PHP entities
  12. PHP files
  13. PHP include files
  14. PHP date & time
  15. PHP cookies
  16. PHP databases
  17. PHP sessions
  18. PHP summary

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 tutorial 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 or cookies 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.

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.

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

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 of destroying an entire session:
<?php session_destroy(); ?>
© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information