search
HomeBackend DevelopmentPHP Tutorialphp for HTTP authentication

PHP 的 HTTP 认证机制仅在 PHP 以 Apache 模块方式运行时才有效,因此该功能不适用于 CGI 版本。在 Apache 模块的 PHP 脚本中,可以用 header() 函数来向客户端浏览器发送“Authentication Required”信息,使其弹出一个用户名/密码输入窗口。当用户输入用户名和密码后,包含有 URL 的 PHP 脚本将会加上预定义变量PHP_AUTH_USER,PHP_AUTH_PW 和 AUTH_TYPE 被再次调用,这三个变量分别被设定为用户名,密码和认证类型。预定义变量保存在 $_SERVER 或者$HTTP_SERVER_VARS 数组中。支持“Basic”和“Digest”(自 PHP 5.1.0 起)认证方法。

Note: PHP 版本问题

Autoglobals 全局变量,包括 $_SERVER等,自 PHP 4.1.0 起有效,$HTTP_SERVER_VARS 从 PHP 3 开始有效。

以下是在页面上强迫客户端认证的脚本范例:

Example #1 Basic HTTP 认证范例

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

在浏览器地址栏输入脚本在服务器位置,弹出如下输入框:

 php for HTTP authentication

如果点击取消的话输出:

Text to send if user hits Cancel Button

如果输入用户名和密码,点击登录:

Hello hello.

You entered world as your password.

Example #2 Digest HTTP 认证范例

本例演示怎样实现一个简单的 Digest HTTP 认证脚本。

<?php
    $realm = &#39;Restricted area&#39;;
    //user => password
    $users = array(&#39;admin&#39; => &#39;mypass&#39;, &#39;guest&#39; => &#39;guest&#39;);
    if (empty($_SERVER[&#39;PHP_AUTH_DIGEST&#39;])) {
        header(&#39;HTTP/1.1 401 Unauthorized&#39;);
        header(&#39;WWW-Authenticate: Digest realm="&#39;.$realm.
            &#39;" qop="auth" nonce="&#39;.uniqid().&#39;" opaque="&#39;.md5($realm).&#39;"&#39;);
        die(&#39;Text to send if user hits Cancel button&#39;);
    }
    // analyze the PHP_AUTH_DIGEST variable
    if (!($data = http_digest_parse($_SERVER[&#39;PHP_AUTH_DIGEST&#39;])) ||
        !isset($users[$data[&#39;username&#39;]]))
        die(&#39;Wrong Credentials!&#39;);
    // generate the valid response
    $A1 = md5($data[&#39;username&#39;] . &#39;:&#39; . $realm . &#39;:&#39; . $users[$data[&#39;username&#39;]]);
    $A2 = md5($_SERVER[&#39;REQUEST_METHOD&#39;].&#39;:&#39;.$data[&#39;uri&#39;]);
    $valid_response = md5($A1.&#39;:&#39;.$data[&#39;nonce&#39;].&#39;:&#39;.$data[&#39;nc&#39;].&#39;:&#39;.$data[&#39;cnonce&#39;].&#39;:&#39;.$data[&#39;qop&#39;].&#39;:&#39;.$A2);
    if ($data[&#39;response&#39;] != $valid_response)
        die(&#39;Wrong Credentials!&#39;);
    // ok, valid username & password
    echo &#39;Your are logged in as: &#39; . $data[&#39;username&#39;];
    // function to parse the http auth header
    function http_digest_parse($txt)
    {
        // protect against missing data
        $needed_parts = array(&#39;nonce&#39;=>1, &#39;nc&#39;=>1, &#39;cnonce&#39;=>1, &#39;qop&#39;=>1, &#39;username&#39;=>1, &#39;uri&#39;=>1, &#39;response&#39;=>1);
        $data = array();
        preg_match_all(&#39;@(\w+)=([\&#39;"]?)([a-zA-Z0-9=./\_-]+)\2@&#39;, $txt, $matches, PREG_SET_ORDER);
        foreach ($matches as $m) {
             $data[$m[1]] = $m[3];
             unset($needed_parts[$m[1]]);
        }
        return $needed_parts ? false : $data;
    }
?>

Note: 兼容性问题

在编写 HTTP 标头代码时请格外小心。为了对所有的客户端保证兼容性,关键字“Basic”的第一个字母必须大写为“B”,分界字符串必须用双引号(不是单引号)引用;并且在标头行 HTTP/1.0 401 中,在 401 前必须有且仅有一个空格。

在以上例子中,仅仅只打印出了 PHP_AUTH_USER 和 PHP_AUTH_PW 的值,但在实际运用中,可能需要对用户名和密码的合法性进行检查。或许进行数据库的查询,或许从 dbm 文件中检索。

注意有些 Internet Explorer 浏览器本身有问题。它对标头的顺序显得似乎有点吹毛求疵。目前看来在发送 HTTP/1.0 401 之前先发送 WWW-Authenticate 标头似乎可以解决此问题。

自 PHP 4.3.0 起,为了防止有人通过编写脚本来从用传统外部机制认证的页面上获取密码,当外部认证对特定页面有效,并且安全模式被开启时,PHP_AUTH 变量将不会被设置。但无论如何,REMOTE_USER 可以被用来辨认外部认证的用户,因此可以用 $_SERVER['REMOTE_USER'] 变量。

Note: 配置说明

PHP 用是否有 AuthType 指令来判断外部认证机制是否有效。

注意,这仍然不能防止有人通过未认证的 URL 来从同一服务器上认证的 URL 上偷取密码。

Netscape Navigator 和 Internet Explorer 浏览器都会在收到 401 的服务端返回信息时清空所有的本地浏览器整个域的 Windows 认证缓存。这能够有效的注销一个用户,并迫使他们重新输入他们的用户名和密码。有些人用这种方法来使登录状态“过期”,或者作为“注销”按钮的响应行为。

Example #3 强迫重新输入用户名和密码的 HTTP 认证的范例

<?php
    function authenticate() {
        header(&#39;WWW-Authenticate: Basic realm="Test Authentication System"&#39;);
        header(&#39;HTTP/1.0 401 Unauthorized&#39;);
        echo "You must enter a valid login ID and password to access this resource\n";
        exit;
    }
    if (!isset($_SERVER[&#39;PHP_AUTH_USER&#39;]) ||
        ($_POST[&#39;SeenBefore&#39;] == 1 && $_POST[&#39;OldAuth&#39;] == $_SERVER[&#39;PHP_AUTH_USER&#39;])) {
        authenticate();
    } else {
        echo "<p>Welcome: {$_SERVER[&#39;PHP_AUTH_USER&#39;]}<br />";
        echo "Old: {$_REQUEST[&#39;OldAuth&#39;]}";
        echo "<form action=&#39;{$_SERVER[&#39;PHP_SELF&#39;]}&#39; METHOD=&#39;post&#39;>\n";
        echo "<input type=&#39;hidden&#39; name=&#39;SeenBefore&#39; value=&#39;1&#39; />\n";
        echo "<input type=&#39;hidden&#39; name=&#39;OldAuth&#39; value=&#39;{$_SERVER[&#39;PHP_AUTH_USER&#39;]}&#39; />\n";
        echo "<input type=&#39;submit&#39; value=&#39;Re Authenticate&#39; />\n";
        echo "</form></p>\n";
    }

该行为对于 HTTP 的 Basic 认证标准来说并不是必须的,因此不能依靠这种方法。对 Lynx 浏览器的测试表明 Lynx 在收到 401 的服务端返回信息时不会清空认证文件,因此只要对认证文件的检查要求没有变化,只要用户点击“后退”按钮,再点击“前进”按钮,其原有资源仍然能够被访问。不过,用户可以通过按“_”键来清空他们的认证信息。

同时请注意,在 PHP 4.3.3 之前,由于微软 IIS 的限制,HTTP 认证无法工作在 IIS 服务器的 CGI 模式下。为了能够使其在 PHP 4.3.3 以上版本能够工作,需要编辑 IIS 的设置“目录安全”。点击“编辑”并且只选择“匿名访问”,其它所有的复选框都应该留空。

另一个限制是在 IIS 的 ISAPI 模式下使用 PHP 4 的时候,无法使用 PHP_AUTH_* 变量,而只能使用 HTTP_AUTHORIZATION。例如,考虑如下代码:list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));。

Note: IIS 注意事项
要 HTTP 认证能够在 IIS 下工作,PHP 配置选项 cgi.rfc2616_headers 必须设置成 0(默认值)。

Note:

如果安全模式被激活,脚本的 UID 会被加到 WWW-Authenticate 标头的 realm 部分。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function