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

时间:2013-08-16 16:37:39

标签: php redirect basic-authentication

如何编写用于计算用户在基本身份验证表格中输入的PHP代码以及第3次重定向到另一个页面后? 所以必须像算法一样:

  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 {
    
        }
    ?>
    
  4. 这是对的吗?

2 个答案:

答案 0 :(得分:2)

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

?>

答案 1 :(得分:0)

您可以使用

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

但是,如果用户没有正确登录3次,你需要确保你的'if'语句带有'else'语句。

相关问题