PHP 从基本授权中获取用户名

PHP get username from Basic Authorization

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

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

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

并且 .htpasswd 文件具有有效的 user/password。

当我转到 PHP 文件时,我需要获取用于访问该页面的用户名。 PHP 访问正常,所以我知道 user/pass 正在工作,但我似乎无法提取用户名。

$_SERVER['REMOTE_USER']$_SERVER['PHP_AUTH_USER']我都试过了,但是都是空的。我怎样才能使这项工作?

已解决。我在 .htaccess 到 运行 php 5.5 中有一个覆盖,它在 CGI 下 运行ning 阻止了授权变量的传递。

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 http://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;
}