Php 简明教程
PHP – HTTP Authentication
在 PHP 中,header() 函数用于向客户端浏览器发送一个“需要验证”的消息,导致出现一个用户名/密码输入窗口。事实上,header() 允许你发送任何原始 HTTP 标头。
In PHP, the header() function is used to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. In fact header() allows you to send any raw HTTP header.
header(string $header, bool $replace = true, int $response_code = 0): void
字符串参数将传递给 header() 函数。例如
The string parameter is passed to the header() function. For example
header("HTTP/1.1 404 Not Found");
它用于找出要发送的 HTTP 状态代码。
It is used to figure out the HTTP status code to send.
还可以使用 header() 函数将浏览器重定向到另一个 URL。
You can also use header() function to redirect the browser to another URL.
一旦用户输入了用户名和密码,包含 PHP 脚本的 URL 将再次被调用,其中预定义变量 PHP_AUTH_USER、PHP_AUTH_PW 和 AUTH_TYPE 分别设置为用户名、密码和验证类型。这些预定义变量在 $_SERVER 数组中找到。仅支持“Basic”和“Digest”身份验证方法。
Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER array. Only "Basic" and "Digest" authentication methods are supported.
<?php
/* Redirect browser */
header("Location: http://www.example.com/");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
可选的替换参数表明标头是否应该替换先前的类似标头或添加第二个相同类型的标头,并且响应代码参数将 HTTP 响应代码强制为指定的值。
The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type, and response_code parameter forces the HTTP response code to the specified value.
为了能够强制客户端身份验证,需要在文档根文件夹中使用 .htaccess 文件。打开一个新文本文档,将以下文本放入其中,并以 .htaccess 为其名称保存。
To be able to force he client authentication, you need a .htaccess file in document root folder. Open a new text file, put the following text in it, and save it with .htaccess as its name.
CGIPassAuth On
Example
强制页面上客户端身份验证的一个示例脚本片段如下所示:
An example script fragment which would force client authentication on a page is as follows −
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'User hits Cancel button';7
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
Output
当你在浏览器中访问脚本时,就会弹出一个对话框,如下所示:
When you visit the script in a browser, it pops up a dialog box as shown −
一旦你点击了登录按钮,可能会有一个后端脚本来验证登录凭据。一旦身份验证通过,将创建两个服务器变量,其键为 PHP_AUTH_USER 和 PHP_AUTH_PW,可以使用 phpinfo() 函数的输出对其进行验证。
Once you click on the sign in button, there may be a backend script to authenticate the login credentials. Once authenticated, two server variables will be created with the keys PHP_AUTH_USER and PHP_AUTH_PW, which can be verified with the output of phpinfo() function.