Search code examples
phpsessionauthenticationlogoutdestroy

Destroy session in php


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

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