Search code examples
phpapachenginxhttp-authentication

HTTP authentication with PHP not work on server


I use the Runcloud as my VPS control panel. then my environment is "NGINX + Apache2 Hybrid"

I use these code to do the authentication on my localhost , it works. But when I deploy(upload) it to the server , it fail. I input the correct username and password and it pop up the window and let me input again util I click "Cancel" button and turn to the fail page.

How can I debug this (check the input username password) ? Or I need to add setting to the server.

<?php
$protect = true;
if($protect){
        $LoginSuccessful = false;

        if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){

            $Username = $_SERVER['PHP_AUTH_USER'];
            $Password = $_SERVER['PHP_AUTH_PW'];

            if ($Username == 'hello' && $Password == 'hello'){
                $LoginSuccessful = true;
            }
        }
        if (!$LoginSuccessful){

            header('WWW-Authenticate: Basic realm="Secret page"');
            header('HTTP/1.0 401 Unauthorized');

            print "Login failed!\n";
            die();
        }
    };
?>
<html code>

Solution

  • Did you add some configuration like

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    

    in apache (not sure what is the equivalent in nginx) Try to dump the

    $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] and see if they are set.