PHP:HTTP Basic - 注销

Par*_*roX 5 php session http

我想设置它,如果有人发送请求"注销"它会自动将他们带到一个页面说"成功注销".如果客户试图按后退按钮或转到限制区域,它将再次请求HTTP身份验证.

到目前为止我所拥有的是:

example.com/restricted/index.php:

<?php   
    session_start();

    if(isset($_GET['logout']))
    {
        unset($_SESSION["login"]);
        header("location: ../logout.php");
        exit;
    }

    if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_SESSION["login"]))
    {

        header("HTTP/1.0 401 Unauthorized");
        header("WWW-authenticate: Basic realm=\"Tets\"");
        header("Content-type: text/html");
        $_SESSION["login"] = true;
        // Print HTML that a password is required
        exit;
    }
?>
// The rest of the page is then displayed like normal
Run Code Online (Sandbox Code Playgroud)

用户成功访问example.com/logout.php 如果example.com/restricted/index.php?logout被访问.当用户尝试返回时,随机事情会发生,有时它会要求两次HTTP身份验证(???),有时它会继续要求在循环中进行身份验证(?),有时它会让我回去,好像我从未退出.

我不熟悉会话是如何工作的,但我的理解是这样的:如果/当这个人被验证时,它会在一个名为login的会话中存储一个变量为true的变量......如果每个人都获得一个带注销的GET请求,它将会然后删除该会话变量并返回logout.php ...为什么当我点击返回索引时它会让我回来而不要求进行身份验证,因为会话[登录]应该没有设置.

对此PHP代码的任何改进都表示赞赏.我知道我不应该使用HTTP Basic并且应该包含SQL,但是meh.这是一个临时解决方案.

编辑:如果包含带有说明的示例,我将接受MySQL的解决方案.我还没有MySQL或PHP数据库知识(还)

Luk*_*son 1

一个粗略的想法让你开始:

<?php   
  session_start();

  if( isset( $_GET['logout'] ) )
  {
    session_destroy();
    header('Location: ../logout.php');
    exit;
  }

  if( !isset( $_SESSION['login'] ) )
  {
    if( !isset( $_SERVER['PHP_AUTH_USER'] ) || !isset( $_SERVER['PHP_AUTH_PW'] ) )
    {
      header("HTTP/1.0 401 Unauthorized");
      header("WWW-authenticate: Basic realm=\"Tets\"");
      header("Content-type: text/html");
      // Print HTML that a password is required
      exit;
    }
    else
    {
      // Validate the $_SERVER['PHP_AUTH_USER'] & $_SERVER['PHP_AUTH_PW']
      if( $_SERVER['PHP_AUTH_USER']!='TheUsername'
          || $_SERVER['PHP_AUTH_PW']!='ThePassword' )
      {
        // Invalid: 401 Error & Exit
        header("HTTP/1.0 401 Unauthorized");
        header("WWW-authenticate: Basic realm=\"Tets\"");
        header("Content-type: text/html");
        // Print HTML that a username or password is not valid
        exit;
      }
      else
      {
        // Valid
        $_SESSION['login']=true;
      }
    }
  }
?>
// The rest of the page is then displayed like normal
Run Code Online (Sandbox Code Playgroud)