PHP从基本授权获取用户名 [英] PHP get username from Basic Authorization

查看:82
本文介绍了PHP从基本授权获取用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的.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 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;
}

这篇关于PHP从基本授权获取用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆