HOWTO · PHP

PHP 身份驗證

本教程演示瞭如何在 PHP 中使用基本的 HTTP 身份驗證。

HTTP 身份驗證向客戶端傳送特殊的 HTTP 標頭,並要求提供身份驗證程式碼以訪問該頁面。

它是一種 PHP 內建方法,用於驗證使用者是否執行特定任務。PHP 有兩種 HTTP 身份驗證方法,BasicDigest

HTTP 身份驗證將生成一個彈出視窗來詢問身份驗證資訊。

它使用陣列 $_SERVER 變數、PHP_AUTH_USERPHP_AUTH_PW 對使用者進行身份驗證,並使用 AUTH_TYPE 設定身份驗證型別。

在 PHP 中使用基本 HTTP 身份驗證對使用者進行身份驗證

基本 HTTP 身份驗證使用非加密 PHP base64 編碼;這就是為什麼它應該只在提供 HTTPS 等安全性時使用。

這些證券稱為傳輸層證券。

<?php

if( ( isset($_SERVER['PHP_AUTH_USER'] ) && ( $_SERVER['PHP_AUTH_USER'] == "admin" ) ) AND ( isset($_SERVER['PHP_AUTH_PW'] ) && ( $_SERVER['PHP_AUTH_PW'] == "password" )) )

{

    echo(" Hello ".$_SERVER['PHP_AUTH_USER']."! <br>\n");

}
else
{
    // These headers will cause the browser to ask for authentication information
    header('WWW-Authenticate: Basic realm="This page is only authorized to registered users"');
    header('HTTP/1.0 401 Unauthorized');

    //This text will be shown after several failed attempts, or you cancel the pop-up box.
    echo"Protected by HTTP Authentication <br>";
	echo "Use <b>admin</b> for the username, and <b>password</b> for the password to enter";
    }
?>

此程式碼將生成一個彈出框並詢問使用者名稱和密碼。

如果輸入正確的資訊,你將可以訪問頁面,如果輸入錯誤,程式碼將重定向幾次,最後列印失敗訊息。

使用者名稱是 admin,密碼是 password

輸出:

PHP 函式警告訊息

If the information is correct:
"Hello admin!" 
If the information is failed:
"Protected by HTTP Authentication"
"Use admin for the username, and password for the password to enter."

在 PHP 中使用 Digest HTTP 身份驗證對使用者進行身份驗證

摘要認證通過對資訊使用雜湊函式來使用加密。

此資訊包括使用者資訊、HTTP 方法、伺服器提供的 nonce 值和請求的 URL;它比基本 HTTP 身份驗證更安全,因為資訊是加密的。

// User authentication info
$auth_info = array('user1' => 'pass1', 'user2' => 'pass2');

// First of all check PHP_AUTH_DIGEST variable, if it is empty the header will redirect the page to pop up box.
if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('WWW-Authenticate: Digest realm="Restricted area",qop="auth",nonce="'.uniqid().'",opaque="'.md5("Restricted area"));
    header('HTTP/1.1 401 Unauthorized');

    exit('You cancelled the authentication');
}

// it is required to check the Digest Authentication Variable first before converting the information to md5

if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($auth_info[$data['username']])){
    exit('The authentication information entered is not correct!');
}

// generating the valid authentication response using the client info and server request method

$auth_hash1 = md5($data['username'] . ':Restricted area:' . $auth_info[$data['username']]);
$auth_hash2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$auth_response = md5($auth_hash1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$auth_hash2);

if ($data['response'] != $auth_response){
    exit('The authentication information entered is not correct!');
}
else{
// if authentication response matches the info 
    echo 'Welcome ' . $data['username'].' you are an authenticated user';
}

// The function below is from the official PHP manual, https://www.php.net/manual/en/features.http-auth.php. It is used to parse the HTTP digest.
function http_digest_parse($txt)
{
    
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}

上面的程式碼顯示了應用摘要 HTTP 身份驗證方法的過程。你可以使用 PHP 手冊中的 http_digest_parse() 函式並使用它來解析 HTTP Digest 身份驗證。

輸出將與基本類似,但更安全。有兩個使用者,user1user2

有兩個密碼,分別是 pass1pass2。你可以輸入任何資訊並登入。

輸出:

PHP 函式警告訊息

If the information is correct:
"Welcome admin you are an authenticated user"
If the information is failed:
"The authentication information entered is not correct!"
If you cancel the pop up:
"You cancelled the authentication"