在php中销毁会话

时间:2014-01-20 11:54:01

标签: php session login logout destroy

我已经看到很多这方面的问题,而且我仍然遇到问题......有人可以给我一个帮助吗?

登录页面:

<?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");
        }
    }
?>

退出页面

<?php
    session_start();

    $_SESSION = array();

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

    Header("Location: login.php");

    exit();
?>

我收到此错误:

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

3 个答案:

答案 0 :(得分:0)

您不必制作$_SESSION = array();

只需使用session_destroy(),如下所示: http://www.php.net/manual/fr/function.session-destroy.php

答案 1 :(得分:0)

这是我用来注销的功能:

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;
}

答案 2 :(得分:0)

这是我通常的方法,请参阅评论以获取更多详细信息。

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