简体   繁体   English

PHP的Http身份验证无法正常工作

[英]Http Authentication with PHP not working

I have Plesk Server where PHP is running as a CGI. 我有Plesk服务器,其中PHP作为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? 怎么解决?

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. 这显然是由于使用CGI。 http://www.besthostratings.com/articles/http-auth-php-cgi.html http://www.besthostratings.com/articles/http-auth-php-cgi.html

.htaccess: 的.htaccess:

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

PHP: PHP:

list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));

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. 只需将它包含在index.php之前。

尝试将beow行添加到.htaccess文件中

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

Did you considered using more standard .htaccess / .htpassword files (if you're using Apache)? 您是否考虑过使用更多标准的.htaccess / .htpassword文件(如果您使用的是Apache)? http://httpd.apache.org/docs/2.0/howto/auth.html 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. 这里$ _SERVER ['PHP_AUTH_USER']似乎永远不会被设置,因此它将始终显示此弹出窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM