Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Sessions in PHP

What are Sessions?

Sessions are a way to store information (in variables) to be used across multiple pages. Unlike cookies, the information is not stored on the user's computer. Session information is stored on the server and can be accessed throughout the user's browsing session.

Starting a Session

Before you can store any information in a session, you must first start the session using the session_start() function. This function must be called at the beginning of the script, before any HTML tags.

Example:

<?php
session_start();
?>
                

Storing Session Variables

Session variables are set using the global $_SESSION array. You can store any type of data in a session variable.

Example:

<?php
session_start();
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john.doe@example.com";
echo "Session variables are set.";
?>
                

Accessing Session Variables

Once a session variable is set, you can access it on any page within the same session.

Example:

<?php
session_start();
echo "Username: " . $_SESSION["username"];
echo "Email: " . $_SESSION["email"];
?>
                

Destroying a Session

If you want to destroy all the session variables and end the session, you can use the session_destroy() function. This function does not unset any of the global variables associated with the session, nor does it unset the session cookie. To completely destroy the session, you will need to use session_unset() as well.

Example:

<?php
session_start();
session_unset();
session_destroy();
echo "Session destroyed.";
?>
                

Setting Session Timeout

You can set a timeout for a session to ensure it expires after a certain period of inactivity. This is done using PHP's ini_set() function.

Example:

<?php
session_start();
ini_set('session.gc_maxlifetime', 1800); // Set session timeout to 30 minutes
?>
                

Storing Complex Data in Sessions

Sessions can store more complex data types like arrays and objects. PHP automatically serializes complex data types when storing them in a session.

Example:

<?php
session_start();
$_SESSION["user"] = array("name" => "John Doe", "email" => "john.doe@example.com");
echo "Complex session data stored.";
?>