0

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?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Nadia
  • 33
  • 1
  • 4
  • 1
    If you want to unset all of the values, you can just run a `session_destroy()`. It will unset all the values and destroy the session. – Phiter Mar 03 '16 at 16:59
  • Possible duplicate of [how to delete all cookies of my website in php](http://stackoverflow.com/questions/2310558/how-to-delete-all-cookies-of-my-website-in-php) – Rohan Khude Mar 03 '16 at 17:01
  • But the `$_SESSION` array will still work in the same page after `session_destroy()`. Then you can simply run `$_SESSION = array()` to reset it's contents. – Phiter Mar 03 '16 at 17:01
  • 1
    Possible duplicate remove request - it doesn't include session destroying, only cookies. Here author asked for sessions & cookies – Muhammed Mar 03 '16 at 17:11
  • @Phiter : As the answer below correctly cites from the manual, `session_destroy()` does _NOT_ delete the session cookie. – András Aszódi Jul 31 '19 at 14:37

1 Answers1

2

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.

Phiter
  • 14,570
  • 14
  • 50
  • 84
Muhammed
  • 1,592
  • 1
  • 10
  • 18