Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Sessions in PHP

Introduction to 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. Sessions are used to store user information to be used across multiple pages (e.g., username, favorite color, etc.). By default, session variables last until the user closes the browser.

Starting a Session

A session is started with the session_start() function. Session variables are set with the global $_SESSION variable.

Example:

<?php
session_start();
?>

This function must be called before any HTML tags. Once started, you can set session variables using the $_SESSION superglobal array.

Setting Session Variables

After starting a session, you can set session variables.

Example:

<?php
session_start();
$_SESSION['username'] = 'JohnDoe';
echo 'Session variables are set.';
?>
Session variables are set.

Accessing Session Variables

You can access session variables from any page. Simply start the session and use the session variables.

Example:

<?php
session_start();
echo 'Username is ' . $_SESSION['username'];
?>
Username is JohnDoe

Modifying Session Variables

If you need to change a session variable, just overwrite it.

Example:

<?php
session_start();
$_SESSION['username'] = 'JaneDoe';
echo 'Username is ' . $_SESSION['username'];
?>
Username is JaneDoe

Destroying a Session

To end a session and clear all session variables, use the session_destroy() function.

Example:

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

This will destroy the session, but to remove existing session variables, you must unset them.

Unsetting Session Variables

To remove a specific session variable, use the unset() function.

Example:

<?php
session_start();
unset($_SESSION['username']);
echo 'Session variable username is unset.';
?>
Session variable username is unset.