Question

i ve seen so many questions about this and im still having problems with that... can someone give me a help?

login page :

<?PHP
    header("Content-Type: text/html; charset=utf-8");
    $login = "root";
    $senha = "test";
    session_start();
    session_set_cookie_params(0);

    if ($_POST['login'] && $_POST['senha']) {
        if ($login == $_POST['login'] && $senha == $_POST['senha']) {

        $_SESSION['login'] = $login;
        $_SESSION['senha'] = $senha;
        Header("Location: index.php");

        } else {
            unset ($_SESSION['login']);
            unset ($_SESSION['senha']);
            header("Location: login.php");
        }
    }
?>

logout page :

<?php
    session_start();

    $_SESSION = array();

    unset( $_SESSION['login'] );
    unset( $_SESSION['senha'] );
    setcookie(session_name(), '', time() - 3600, '/');
    session_destroy();

    Header("Location: login.php");

    exit();
?>

im getting this error:

PHP Warning:  session_destroy(): Session object destruction failed in \\N\Users\cPanel\gil\public_html\gilberto\logout.php on line 11
Was it helpful?

Solution

This is my usual approach, see the comments for further details.

session_start();

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

// 2. delete the session 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'] );
}

// 3. destroy the session.
session_destroy();

OTHER TIPS

You don't have to make $_SESSION = array();

Just use session_destroy() like said here : http://www.php.net/manual/fr/function.session-destroy.php

Here is a function i use to logout:

function logout(){

    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);

        if(strtoupper($name) == 'PHPSESSID'){
            continue;
        }

        setcookie($name, '', time()-360000);
        setcookie($name, '', time()-360000, '/');
    }

    foreach($_SESSION as $key => $val){
        unset($_SESSION[$key]);
    }

    header('Location: account/login');
    die;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top