Sessions

The Web was designed for browsing documents, where each request from a web browser to a web server was intended to be independent of each other interaction. To develop applications for the Web, additional logic is required so that different requests can be related. For example, code is required to allow a user to log in, use the application, and log out when she’s finished. In PHP, this logic is provided by the sessions library. Sessions allow variables to be stored on the server, so that these variables can be restored each time a user requests a script. Consider a short example:

<?php
 // Initialize the session
 session_start();

 // If there is no "count" session variable, create one, and welcome
 // the user.
 if (!isset($_SESSION["count"]))
 {
  $_SESSION["count"] = 0;
  echo "Welcome new user!";
 }
 // Otherwise, increment the number of visits and display a message.
 else
 {
  $_SESSION["count"]++;
  echo "Hello! You've visited this page {$_SESSION["count"]} times before.";
 }
?>

The session_start function activates an existing session or, if none exists, creates a new one. When the user requests the script for the first time, the $_SESSION["count"] variable does not exist, so the isset() function returns the value FALSE. A new session is created, and a new session variable count is defined in the $_SESSION superglobal array, with its value set to 0. Session variables are stored on the web server; when the user next requests the script, the isset() function returns TRUE, the $_SESSION["count"] ...

Get Learning MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.