skip to Main Content

I have Plesk Server where PHP is running as a CGI.

    if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}

The above script should prompt the user name and password. (Yes it does)
After entering any user/pass it should print them. (No, it always ask for the user/pass)

How to fix it?

4

Answers


  1. Did you considered using more standard .htaccess / .htpassword files (if you’re using Apache)?
    http://httpd.apache.org/docs/2.0/howto/auth.html

    Here $_SERVER[‘PHP_AUTH_USER’] looks to be never setted, so it will always display this popup.

    Login or Signup to reply.
  2. Here is the file I include before anything in any project that is under development:

    <?php
    
    // protecting page of unauthorized access
    
    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){ 
        $user = $_SERVER['PHP_AUTH_USER'];
        $pass = $_SERVER['PHP_AUTH_PW'];
    
        if ($user == 'username' && $pass == 'dev'){
            return;
        }
    }
    
    header('WWW-Authenticate: Basic realm="Protected zone"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Login failed.';
    exit;
    

    Just include it in your index.php before anything else.

    Login or Signup to reply.
  3. I’ve got this problem too on one of my servers and the following solved it for me. It’s apparently due to using CGI.
    http://www.besthostratings.com/articles/http-auth-php-cgi.html

    .htaccess:

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

    PHP:

    list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
    
    Login or Signup to reply.
  4. Try adding beow line to your .htaccess file

    SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search