Sessions in php

PHP has built-in support for sessions, handling all the cookie manipulation for you to provide persistent variables that are accessible from different pages and across multiple visits to the site. Sessions allow you to easily create multipage forms (such as shopping carts), save user authentication information from page to page, and store persistent user preferences on a site

Each first-time visitor is issued a unique session ID. By default, the session ID is stored in a cookie called PHPSESSID. If the user’s browser does not support cookies or has cookies turned off, the session ID is propagated in URLs within the website.

Every session has a data store associated with it. You can register variables to be loaded from the data store when each page starts and saved back to the data store when the page ends. Registered variables persist between pages, and changes to variables made on one page are visible from others. For example, an “add this to your shopping cart” link can take the user to a page that adds an item to a registered array of items in the cart. This registered array can then be used on another page to display the contents of the cart.

Session basics

Sessions are started automatically when a script begins running. A new session ID is generated if necessary, possibly creating a cookie to be sent to the browser, and loads any persistent variables from the store.

You can register a variable with the session by passing the name of the variable to the $_SESSION[ ] array. For example, here is a basic hit counter:

$_SESSION[‘hits’] = $_SESSION[‘hits’] + 1;
echo “This page has been viewed {$_SESSION[‘hits’]} times.”;

The session_start() function loads registered variables into the associative array $_SESSION. The keys are the variables’ names (e.g., $_SESSION[‘hits’]). If you’re curious, the session_id() function returns the current session ID

Example of Setting preferences with sessions

<head><title>Preferences Set</title></head>
$colors = array(
 'black' => "#000000",
 'white' => "#ffffff",
 'red' => "#ff0000",
 'blue' => "#0000ff"
$backgroundName = $_POST['background'];
$foregroundName = $_POST['foreground'];
$_SESSION['backgroundName'] = $backgroundName;
$_SESSION['foregroundName'] = $foregroundName;

<p>Thank you. Your preferences have been changed to:<br />
Background: <?= $backgroundName; ?><br />
Foreground: <?= $foregroundName; ?></p>
<p>Click <a href="prefs_session_demo.php">here</a> to see the preferences
in action.</p>

Leave a Comment