错误登录后的基本身份验证重定向


Basic Authentication redirection after wrong logins

如何编写php代码,计算用户以基本身份验证形式输入的内容,并在第三次重定向到另一个页面后?所以必须是像这样的算法:

  1. 如果出现3次错误登录,请转到example.com
  2. 如果登录正确,请访问host.com/page1.php
  3. 如果按取消,则返回"<h1>Authorization Required</h1>";

    session_start();
    if(isset($_SESSION['login_attempts'])){ $_SESSION['login_attempts']++; }else{$_SESSION['login_attempts'] = 1;}
    if($_SESSION['login_attempts'] == 3 && $login_failed == true){
        header('Location: http://www.example.com');
        die;
    }
    $_user = 'test1324546';
    $_password = 'test23456';
    if ($_SERVER['PHP_AUTH_USER'] != $_user|| $_SERVER['PHP_AUTH_PW'] != $_password ) {    
    header('WWW-Authenticate: Basic realm="hi"');
    header('HTTP/1.0 401 Unauthorized');
    echo "<html><head><title>401 Authorization Required</title></head><body>";
    echo "<h1>Authorization Required</h1>";
    exit;
        } else {
        }
    ?>
    

这是正确的吗?

使用会话将是最简单的方法,但这不会阻止机器人,因为它们会清除会话cookie。

下面是一些示例代码。

<?php
    session_start();
    $_user = 'test1324546';
    $_password = 'test23456';
    if ($_SERVER['PHP_AUTH_USER'] != $_user || $_SERVER['PHP_AUTH_PW'] != $_password ) {
        if(isset($_SESSION['login_attempts'])){ $_SESSION['login_attempts']++; }else{$_SESSION['login_attempts'] = 1;}
        if($_SESSION['login_attempts'] == 3){
            header('Location: http://www.example.com');
            exit;
        } else {
            header('WWW-Authenticate: Basic realm="hi"');
            header('HTTP/1.0 401 Unauthorized');
            echo "<html><head><title>401 Authorization Required</title></head><body>";
            echo "<h1>Authorization Required</h1>";
            exit;
        }
    } else {
        header('Location: /page1.php');
        exit;
    }
?>

您可以使用

header('Location: page1.php'); /* -- Example -- */

但是,如果用户三次登录都不正确,您需要确保您有一个"if"语句和"else"语句。