如何在 PHP 中使用基本 HTTP 身份验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4150507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:07:21  来源:igfitidea点击:

How can I use Basic HTTP Authentication in PHP?

phpauthenticationhttp-authenticationbasic-authenticationserver-variables

提问by Jonas

I'm trying to use Basic HTTP Authenticationand followed the example on the PHP manual page. But it doesn't work for me. The variable $_SERVER['PHP_AUTH_USER']doesn't seem to be set. When a user try to log in, the user is prompted whith a new login-dialog. The server is running PHP 5.3.3 and I have tried with Google Chrome and Internet Explorer.

我正在尝试使用基本 HTTP 身份验证并遵循 PHP 手册页上的示例。但这对我不起作用。变量$_SERVER['PHP_AUTH_USER']似乎没有设置。当用户尝试登录时,会提示用户使用新的登录对话框。服务器运行的是 PHP 5.3.3,我尝试过使用 Google Chrome 和 Internet Explorer。

Here is the simple example that I used:

这是我使用的简单示例:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="Jonas Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'User pressed Cancel';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as you password.</p>";
}
?>

What is wrong? How can I use Basic HTTP Authentication in PHP?

怎么了?如何在 PHP 中使用基本 HTTP 身份验证?

采纳答案by bobince

How is PHP being run? If it's through Apache mod_cgi, I'm afraid you cannot get hold of the authentication information at all. Apache won't pass it to CGI apps unless you compile it with the SECURITY_HOLE_PASS_AUTHORIZATIONflag. (Whether it's actually a security hole or not depends on whether other users on your server have a lower or greater privilege than your website users.)

PHP 是如何运行的?如果是通过Apache mod_cgi,恐怕你根本拿不到认证信息。Apache 不会将其传递给 CGI 应用程序,除非您使用该SECURITY_HOLE_PASS_AUTHORIZATION标志对其进行编译。(它是否真的是一个安全漏洞取决于您服务器上的其他用户是否具有比您的网站用户更低或更高的权限。)

If it's IIS CGI, you have to ensure that only ‘Anonymous' directory access is configured, or IIS will try to step in and authenticate credentials itself.

如果是 IIS CGI,则必须确保仅配置了“匿名”目录访问,否则 IIS 将尝试介入并验证凭据本身。

echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";

HTML-injection security hole (well, if it worked). Use htmlspecialchars(). Man, is that PHP doc page full of highly questionable advice and code.

HTML 注入安全漏洞(好吧,如果有效的话)。使用htmlspecialchars(). 伙计,那个 PHP 文档页面充满了高度可疑的建议和代码。

You can try to look at $_SERVER['HTTP_AUTHORIZATION']as well, though I suspect it's the mod_cgi issue in which case neither variable will be present and you will have to resort to cookie-based login instead. Or change to a host with a more modern approach to PHP hosting, such as FastCGI or mod_php.

您也可以尝试查看$_SERVER['HTTP_AUTHORIZATION'],尽管我怀疑这是 mod_cgi 问题,在这种情况下,两个变量都不存在,您将不得不改用基于 cookie 的登录。或者更改为使用更现代的 PHP 托管方法的主机,例如 FastCGI 或 mod_php。

回答by Mazhar Ahmed

Try this::

尝试这个::

<?php
    /*
    ** Define a couple of functions for
    ** starting and ending an HTML document
    */
    function startPage()
    {
        print("<html>\n");
        print("<head>\n");
        print("<title>Listing 24-1</title>\n");
        print("</head>\n");
        print("<body>\n");
    }

    function endPage()
    {
        print("</body>\n");
        print("</html>\n");
    }
    /*
    ** test for username/password
    */
    if( ( isset($_SERVER['PHP_AUTH_USER'] ) && ( $_SERVER['PHP_AUTH_USER'] == "leon" ) ) AND
      ( isset($_SERVER['PHP_AUTH_PW'] ) && ( $_SERVER['PHP_AUTH_PW'] == "secret" )) )
    {
        startPage();

        print("You have logged in successfully!<br>\n");

        endPage();
    }
    else
    {
        //Send headers to cause a browser to request
        //username and password from user
        header("WWW-Authenticate: " .
            "Basic realm=\"Leon's Protected Area\"");
        header("HTTP/1.0 401 Unauthorized");

        //Show failure text, which browsers usually
        //show only after several failed attempts
        print("This page is protected by HTTP " .
            "Authentication.<br>\nUse <b>leon</b> " .
            "for the username, and <b>secret</b> " .
            "for the password.<br>\n");
    }
?>

回答by Teddy

For PHP-CGI:

对于 PHP-CGI:

in .htaccess add this:

在 .htaccess 中添加:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>

and at the beginning of your script add this:

并在脚本的开头添加:

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

回答by Ankur Kumar Singh

Check if you have overrided your variable $_SERVER[‘PHP_AUTH_USER']and$_SERVER[‘PHP_AUTH_PW']before the place where you are trying to access the both variables.

检查您是否已经覆盖了您的变量$_SERVER[‘PHP_AUTH_USER']以及$_SERVER[‘PHP_AUTH_PW']您尝试访问这两个变量的位置之前。

If above is not the case then chek if you are using php as cgi mod or not. IF you are using php as cgi mod then in the most of case you will not get $_SERVER[‘PHP_AUTH_USER']and$_SERVER[‘PHP_AUTH_PW']because generraly we do not compile the apache with option SECURITY_HOLE_PASS_AUTHORIZATIONSo if you want to get both variable then re-compile apache with option SECURITY_HOLE_PASS_AUTHORIZATION or you can use .htaccess approach explained in PHP basic authpost.

如果上述情况并非如此,请检查您是否使用 php 作为 cgi mod。如果你使用 php 作为 cgi mod 那么在大多数情况下你不会得到$_SERVER[‘PHP_AUTH_USER']$_SERVER[‘PHP_AUTH_PW']因为一般情况下我们不编译带有选项的 apacheSECURITY_HOLE_PASS_AUTHORIZATION所以如果你想获得这两个变量然后重新编译带有选项 SECURITY_HOLE_PASS_AUTHORIZATION 的 apache 或者你可以使用 .在PHP basic authpost 中解释了 htaccess 方法。

回答by Ken Richards

I think the PHP methods rely on Basic Authentication being configured on the Web Server. An easy way to do this is to include a .htaccess file in the directory you want to enable basic authentication for.

我认为 PHP 方法依赖于在 Web 服务器上配置的基本身份验证。一种简单的方法是在要为其启用基本身份验证的目录中包含一个 .htaccess 文件。

Most unix-based web hosts allow you to do this by just uploading this file. A separate file (call this .htauth) will hold the user logins that are allowed to access the site or directory.

大多数基于 unix 的 Web 主机允许您通过上传此文件来执行此操作。一个单独的文件(称为 .htauth)将保存允许访问站点或目录的用户登录名。