Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't end PHP session

Tags:

php

session

ok so I have the following code that echos some session variables that I set already.(They echo like intended.)

(index.php)

<?php session_start();?>
Username: <?php echo $_SESSION['username']; ?><br>
Password(encrypted): <?php echo $_SESSION['password']; ?><br>
ThemeColor: <?php echo $_SESSION['themecolor']; ?><br>


And I have this code which I try to end the session with, but when I run the code above, the variables still echo out, so the session is still active

(logout.php)

<?php
session_start();
session_unset();
session_destroy();
?>


Can you tell me what I'm doing wrong?
like image 492
Veloncia Avatar asked Dec 06 '25 06:12

Veloncia


2 Answers

Straight from the PHP documentation:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>
like image 163
Josh Harrison Avatar answered Dec 08 '25 19:12

Josh Harrison


Keep your existing snippet and try adding the following snippet:

// Clear all values of the $_SESSION array by creating a new one
$_SESSION = array();

// If your session is setup to use cookies, expire the cookie
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

The above snippet was borrowed from it's original answer here. All credit goes to the original author Pekka.

like image 31
War10ck Avatar answered Dec 08 '25 20:12

War10ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!