使用PHP登出设置Cookie的网站

问题描述 投票:1回答:1

很难弄清楚这一点。 我知道将这些信息存储在cookie中不是最佳实践,但这是针对学校项目的,而我的教授只是要求这样做。

这是您登录并设置cookie的代码| admin.php的:

<?php
if (!isset($_COOKIE['loggedIn'])) {
  if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
  } else if($_SERVER['PHP_AUTH_USER'] == "user1" &&
    $_SERVER['PHP_AUTH_PW'] == "pass1") {
    //make the cookie
    setcookie("loggedIn", "user1/pass1", time() + 60);
  } else {
    header('HTTP/1.0 401 Unauthorized');
    echo "Invalid Credentials";
    exit;
  }
} else {
  if (isset($_COOKIE['loggedIn']) && $_COOKIE['loggedIn'] == "user1/pass1") {
   //YAY DO NOTHING ITS ME
  } else {
    header('HTTP/1.0 401 Unauthorized');
    echo "Invalid Credentials";
    exit;
  }
}
?>

这是我尝试运行以删除Cookie和注销的代码,因此当您再次访问admin.php页面时,您将不得不再次输入凭据..但它似乎不起作用。
logout.php:

<?php 

    if(isset($_COOKIE[session_name()])):
            setcookie(session_name(), '', time()-7000000, '/');
        endif;

    if(isset($_COOKIE['loggedIn'])):
        setcookie('loggedIn', '', time()-7000000, '/');
    endif;

    session_start();
    session_unset();
    //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: index.php");

 ?>

在此先感谢您的帮助!

php authentication cookies admin logout
1个回答
0
投票

php.net上有一个非常全面的示例: http : //php.net/manual/en/function.session-destroy.php

<?php
session_start();

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

if(isset($_COOKIE[session_name()])):
    setcookie(session_name(), '', time()-7000000, '/');
endif;

if(isset($_COOKIE['loggedIn'])):
    setcookie('loggedIn', '', time()-7000000, '/');
endif;

// Check session cookies
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();
//session_unset();
//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: index.php");

注意取消设置会话数组:$ _SESSION = array(); 删除会话cookie; 并销毁会话:session_destroy();

谢谢,

安德鲁

© www.soinside.com 2019 - 2024. All rights reserved.