'proper way to logout from a session in PHP

I have read many php tutorials for logout scripts, i am wondering what could be the proper way to logout from a session!

Script 1

<?php
session_start();
session_destroy();
header("location:index.php");
?>

Script 2

<?php
session_start();
session_unset();
session_destroy();
header("location:index.php");
?>

Script 3

<?php
session_start();
if (isset($_SESSION['username']))
{
    unset($_SESSION['username']);
}
header("location:index.php");
?>

Is there any more effective way to do this?? A session can always be created by logging back in, so should i bother about use of session_destroy() and use unset($_SESSION['variable']) instead? which one of the above 3 script is more preferable?



Solution 1:[1]

Personally, I do the following:

session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();

That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

Solution 2:[2]

Session_unset(); only destroys the session variables. To end the session there is another function called session_destroy(); which also destroys the session .

update :

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that

Solution 3:[3]

<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.    
session_destroy();

// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ircmaxell
Solution 2
Solution 3