PHP variables declared inside a script only exist during execution of the script (i.e. for a given page). At the end of the execution, the content of the variables is definitively lost. It is often necessary to have persistent data during navigation. On a merchant site for example, the basket is kept even if the user navigates to a new page or reloads the current page. The PHP sessions allow you to keep this data during navigation from one page to another.
A PHP session alawys starts with the call of the session_start ()
function. The call
of this function must imperatively be the very first instruction of your
script or document, otherwise the sessions will not work. Here is an example :
<?php
// Starts sessions
session_start();
?>
// Your HTML or PHP code
Data stored in session variables can be accessed via the global table $ _SESSION
.
This array can be read and write. The following example
counts the number of times the page has been loaded:
<?php
// Start sessions
session_start();
// If the session already exists, increments the counter
// otherwise initialize the counter
if (isset($_SESSION['counter']))
$_SESSION['counter']++;
else
$_SESSION['counter']=1;
?>
<!-- Display counter -->
You visited this page <?= $_SESSION['counter'] ?> times.
Sessions, as their name suggests, are linked to a user session. When the user closes his browser, the session is automatically destroyed. If the sessions are inactive, they are automatically destroyed after a given time lapse. This lifetime is a parameter of the server, generally set by default on 24 minutes.
It is often necessary to destroy all or part of the session variables. Typicaly when a user logs out. There are two ways to destroy session variables.
The unset
function allows you to destroy a variable while keep the others:
unset( $_SESSION['counter'] );
The session_unset
destroy all the session variables:
session_unset();
This function is equivalent to $_SESSION = array();
.
Complete the following code so that it displays the number of visits
for pages page1.php
and page2.php
: