How to Logout from a Session in PHP

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?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();
?>

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]); // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

PHP session not logging out / unset

I don't know why, but the code for destroying the sessions was somehow not working in logout.php. It worked in index.php and other files, but will all sorts of unpredictable behavior.

Found a workaround to circumvent the problem. The logout.php has code as below:

<?php
session_start();
$_SESSION['logout'] = TRUE;
header('location:index.php');
?>

And add this code to index.php:

# Implement logout functionality
<?php
session_start();
if(isset($_SESSION['logout']) && $_SESSION['logout'] == TRUE){
foreach($_SESSION as $var => $value){
unset($_SESSION[$var]);
}
session_destroy();
session_unset();
}
?>

It may not be a standardized solution, but the code works for me every time, with no unpredictable behavior.

Thanks everyone for sharing their ideas.

Session logout without closing the session

You could add a "temp_logout" field to the $_SESSION variable and when you redirect the user to the login page, you can check for it $_SESSION["temp_logout"] and if it is true, add the username in the input field.

logout script:

<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:login.php")
?>

login page:

session_start()
...
//where the "username" input is
<input name="username" <?php if(isset($_SESSION["temp_logout"]){
echo 'value="'.$_SESSION["username"] .'" ';
} ?> />
...

after a successfull login:

<?php
session_start();
unset($_SESSION["temp_logout"]);
?>

Also, anywhere on the site, don't forget to check if the user is temporarily logged out; then immediatelly redirect him to the login page



Related Topics



Leave a reply



Submit