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

标签 php redirect basic-authentication

如何编写 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 {
    
        }
    ?>
    

正确吗?

最佳答案

使用 session 将是最简单的方法,但这不会阻止机器人,因为它们会清除 session 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;
    }

?>

关于php - 错误登录后的基本身份验证重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18278193/

相关文章:

php - 获得空响应,如果存在 blob 字段 [PHP]

php - JMS序列化器读取xml :lang attribute

redirect - Nginx 将 HTTP 重定向到 HTTPS 并将非 www 重定向到 ww

php - 表单完成后如何重定向到php中的另一个页面?

ruby-on-rails - 在哪里可以存储在 Rails 的 http_basic_authentication_with 中使用的密码/用户名组合?

rest - 基本 HTTP 和不记名 token 身份验证

java - 如何防止Spring Security在每个页面都要求输入密码

带有 vi 键绑定(bind)的 PHP IDE

php - 在哪里注册事件监听器

angular - 打开模式时留在同一页面