PHP Destroy Session

In this chapter you will learn:

  1. Destroy Session
  2. Destroy Session Array
  3. Destroy Session Cookie

Destroy Session

By default PHP sessions are automatically deleted when users quit their browser, because the PHPSESSID cookie's expires field is set to zero.

To destroy a session immediately, you can simply call the session_destroy() function:

session_destroy();

Destroy Session Array

This erases the session data from the disk. The data is still in the $_SESSION array until the current execution of the script ends.

To make sure that all session data has been erased, we should initialize the $_SESSION array:


<?PHP
$_SESSION = array(); 
session_destroy();   
?>

A trace of the session remains in the form of the PHPSESSID cookie in the user's browser. When the user next visits your site, PHP will use the PHPSESSID cookie though the new session won't contain any data when it's recreated.

To wipe the session from both the server and the browser, you should destroy the session cookie:


<?PHP// j  a v  a2 s . c o m
         if ( isset( $_COOKIE[session_name()] ) ) { 
           setcookie( session_name(), "", time()-3600, "/" ); 
         } 

         $_SESSION = array(); 
         session_destroy();  
?>

Next chapter...

What you will learn in the next chapter:

  1. Changing Session Behavior
Home » PHP Tutorial » PHP Session
PHP Session
PHP Access Session Data
PHP Destroy Session
PHP Session Behavior