首页 > 开发 > Apache > 正文

php apache PHP_AUTH_USER用户登录的方法

2020-10-12 18:48:33
字体:
来源:转载
供稿:网友

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

php apache PHP_AUTH_USER用户登录的方法实例代码如下:

  1. <?php 
  2.    $authorized = FALSE; 
  3.  
  4.    if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { 
  5.       $authFile = file("./password.txt"); 
  6.  
  7.       foreach ($authFile as $login) { 
  8.          list($username$password) = explode(":"$login); 
  9.          $password = trim($password); 
  10.          if (($username == $_SERVER['PHP_AUTH_USER']) && ($password == md5($_SERVER['PHP_AUTH_PW']))) { 
  11.             $authorized = TRUE; 
  12.             break
  13.          } 
  14.       } 
  15.    } 
  16.  
  17.    // If not authorized, display authentication prompt or 401 error 
  18.    if (! $authorized) { 
  19.       header('WWW-Authenticate: Basic Realm="Secret Stash"'); 
  20.       header('HTTP/1.0 401 Unauthorized'); 
  21.       print('You must provide the proper credentials!'); 
  22.       exit
  23.    } 
  24.  
  25. ?> 

<!-- password.txt

joe:60d99e58d66a5e0f4f89ec3ddd1d9a80

-->

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表