Nadia
Nadia

Reputation: 33

Deleting session cookies with PHP

This is what I need to be doing: delete all session cookies and destroy the session on the server. delete the session cookie from the browser.

<?php
session_start();
$name = session_name();
$expire = strtotime('-1 year');
$params = session_get_cookie_params();
$path = $params['path'];
$domain = $params['domain'];
$secure = $params['secure'];
$httponly = $params['httponly'];
setcookie($name, '', $expire, $path, $domain, $secure, $httponly);
unset($_SESSION["course_code"]);
unset($_SESSION["course_name"]);
unset($_SESSION["publisher"]);
session_unset();
session_destroy();

?>

Does this properly do what needs to be done?

Upvotes: 0

Views: 5270

Answers (1)

Muhammed
Muhammed

Reputation: 1612

Here you go, you need to delete in a loop:

//when dealing with session always add session_start() on top
session_start();
//From PHP manual: Unset all of the session variables.
//No need to do in a loop for all $_SESSION[] keys
$_SESSION = array();

//For cookies you do similar, from PHP docs:
//http://php.net/manual/en/function.setcookie.php#73484

if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}
session_destroy();

PS: from PHP manual:

Only use session_unset() for older deprecated code that does not use $_SESSION. so don't use that. session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

To be safe call session_​regenerate_​id() upon login, logout, and sensitive areas of the script.

Upvotes: 2

Related Questions