In addition to cookies, sessions can also be used to store user information across multiple HTTP requests. However, sessions are a bit different from cookies. Unlike cookies, sessions store client’s information on the server side and only a reference to that session is stored on the client’s machine. When a client sends a request to the server, the reference of the session is also sent to the server. The server then locally retrieves the session against this reference. This way a large amount of user information can be stored via sessions.
<?php
session_start();
if( isset( $_SESSION['pagevisits'] ) ) {
$_SESSION['pagevisits'] = $_SESSION['pagevisits'] + 1;
} else {
$_SESSION['pagevisits'] = 1;
}
$info = "This is your ". $_SESSION['pagevisits']." page visit on this site.";
$info .= "in the current session";
?>
<?php echo ( $info); ?>
To start a session, session_start() function is called. This initiates the $_SESSION associative array. In this $_SESSION associative array, you can create as many session variables you want. In the above variable a session variable pagevisits has been created. Every time user visits the page, this variable is incremented by 1 and a message is displayed to the user displaying the number of times user has visited the page.
Deleting a Session
There are two ways to delete sessions. You can delete individual session variables by calling unset function and passing it session variable in the $_SESSION associative array. The other way is to delete all the session variables by calling session_destroy function. Have a look at following example.
<?php
session_start();
unset($_SESSION['pagevisits']);
session_destroy();
?>
Now, after executing the above code, if you again run the code in last example, you will see that your page visit will be considered as the first page visit, since this will be a new session.