HomePHP Page 3 - Introduction to Maintaining the State of Applications with PHP Sessions
Ending a session: using the “session_destroy()” function - PHP
In PHP, session management is used to help web applications maintain their state across several HTTP requests when needed. In this first part of a series, you will learn the basics of the PHP built-in session mechanism, as well as some of its many useful functions.
In many situations, the logic of a particular PHP application requires that a specific session be terminated. In order to end an active session, PHP includes the “session_destroy()” function, which as the name indicates, destroys all the data associated with the current session. It’s worth noting that this function doesn’t unset any of the global variables tied to the session or the respective cookie. The use of this function is exemplified below:
session_start(); session_destroy();
As I said before, calling the “session_destroy()” function doesn’t delete the corresponding session variables or associated cookies. Thus a typical script, excerpted from the PHP manual, which destroys the current session along with all the session variables and the cookie associated to it, is listed below:
// destroy a session and all variables and cookies associated with it. session_start(); $_SESSION = array(); if(isset($_COOKIE[session_name()])){ setcookie(session_name(),'', time()-48000,'/'); } session_destroy();
In the above example, all the session variables are unset by the line:
$_SESSION = array();
while the corresponding cookie is deleted by the following code:
Additionally, all the registered session variables can be freed up with the “session_unset()” function. However, for a complete and secure deletion of the entire session, it’s recommended to use the “session_destroy()” function in conjunction with the superglobal $_SESSION array and the “setCookie()” function, as shown in the example above.
Nevertheless, there are some extra issues worth considering when ending sessions. In case the session ID is transmitted by cookies, they will be deleted as soon as the browser is closed. Bearing in mind this condition, you should configure (when possible) the “gc_maxlifetime” and “gc_probability” directives of the php.ini file, in order to instruct PHP to trigger its garbage collection mechanism, in accordance with the requirements of the application being developed.
Fine, at this point, you hopefully learned how to create and destroy an active session. Therefore, let’s move on to the next section and continue exploring a few more handy session functions.