Search code examples
phphttp-redirectbasic-authentication

Basic Authentication redirection after wrong logins


How to write php code which count users input in basic auth form and after 3rd time redirect to another page? So must be algoritm like:

  1. If wrong login comes 3times then goto example.com
  2. If login correct go to host.com/page1.php
  3. If press cancel then echo "<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 {
    
        }
    ?>
    

Is that correct?


Solution

  • Using sessions will be the easiest way but this won't stop bots, as they will clear their session cookie.

    Here is some example code.

    <?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;
        }
    
    ?>