Deleting session cookies with PHP

83

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?

644

Answer

Solution:

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 usesession_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 callsession_​regenerate_​id() upon login, logout, and sensitive areas of the script.

People are also looking for solutions to the problem: php - What is resource id #170?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.