PHP從基本授權獲取用戶名

更新時間:2024-04-01 21:49:10

問題闡述

在我的.htaccess文件中,我有:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
require valid-user

<Files .htaccess>
deny from all 
</Files>

并且.htpasswd文件具有有效的用戶/密碼。

當我轉到一個PHP文件時,我需要獲取用于訪問該頁面的用戶名。可以訪問PHP,ജ所以我知道User/Pass正在工作,但我似乎無法提取用戶名。

我同時嘗試了$_SERVER['REMOTE_USER']$_SERVER['PHP_AUTH_USER'],但都是空的。我如何才能使其正常工作?

php

精準答案可以用不同的方式存儲用戶名,因此可以嘗試一下下面這樣的方法。

<?php

$username_extracted = retrieve_php_username();

function retrieve_php_username() {
  $username = '';
  // Try to get the login name from the $_SERVER variable.
  if (isset($_SERVER['HTTP_AUTHORIZATION']) || isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
    $authorization_header = '';
    if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
      $authorization_header = $_SERVER['HTTP_AUTHORIZATION'];
    }
    // If using CGI on Apache with mod_rewrite, the forwarded HTTP header appears in the redirected HTTP headers.
    elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
      $authorization_header = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    }
    // Resemble PHP_AUTH_USER and PHP_AUTH_PW for a Basic authentication from
    // the HTTP_AUTHORIZATION header. See //www.php.net/manual/features.http-auth.php
    if (!empty($authorization_header)) {
      list($username_temp, $userpass_temp) = explode(':', base64_decode(substr($authorization_header, 6)));
      $username = $username_temp;
    }
  }
  // Check other possible values in different keys of the $_SERVER superglobal
  elseif (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
    $username = $_SERVER['REDIRECT_REMOTE_USER'];
  }
  elseif (isset($_SERVER['REMOTE_USER'])) {
    $username = $_SERVER['REMOTE_USER'];
  }
  elseif (isset($_SERVER['REDIRECT_PHP_AUTH_USER'])) {
    $username = $_SERVER['REDIRECT_PHP_AUTH_USER'];
  }
  elseif (isset($_SERVER['PHP_AUTH_USER'])) {
    $username = $_SERVER['PHP_AUTH_USER'];
  }
  return $username;
}