Home php教程 php手册 php基于表单密码验证与HTTP验证用法实例

php基于表单密码验证与HTTP验证用法实例

Jun 06, 2016 pm 08:14 PM
http php password usage form verify

这篇文章主要介绍了php基于表单密码验证与HTTP验证用法,以实例形式较为详细的分析了表单密码验证与HTTP验证的原理与相关注意事项,具有一定参考借鉴价值,需要的朋

本文实例讲述了php基于表单密码验证与HTTP验证用法。分享给大家供大家参考。具体分析如下:

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

PHP 版本问题: Autoglobals 全局变量,包括 $_SERVER 等,自 PHP 4.1.0 起有效, $HTTP_SERVER_VARS 从 PHP 3 开始有效。

以下是在页面上强迫客户端认证的脚本范例.

例子 34-1. Basic HTTP 认证范例

复制代码 代码如下:

   if (!isset( $_SERVER [ 'PHP_AUTH_USER' ])) { 
     header ( 'WWW-Authenticate: Basic realm="My Realm"' ); 
     header ( 'HTTP/1.0 401 Unauthorized' ); 
    echo 'Text to send if user hits Cancel button' ; 
    exit;
  } else { 
    echo "

Hello { $_SERVER [ 'PHP_AUTH_USER' ]} .

" ; 
    echo "

You entered { $_SERVER [ 'PHP_AUTH_PW' ]} as your password.

" ; 
  } 
?>
例子 34-2. Digest HTTP 认证范例

本例演示怎样实现一个简单的 Digest HTTP 认证脚本,更多信息请参考 RFC 2617.

复制代码 代码如下:

$realm = 'Restricted area' ;
//user => password 
$users = array( 'admin' => 'mypass' , 'guest' => 'guest' );
 
if (!isset( $_SERVER [ 'PHP_AUTH_DIGEST' ])) { 
     header ( 'HTTP/1.1 401 Unauthorized' ); 
     header ( 'WWW-Authenticate: Digest realm="' . $realm . 
            '" qop="auth" nonce="' . uniqid (). '" opaque="' . md5 ( $realm ). '"' );
    die( 'Text to send if user hits Cancel button' ); 
}
// analize the PHP_AUTH_DIGEST variable 
preg_match ( '/username="(?P.*)",s*realm="(?P.*)",s*nonce="(?P.*)",s*uri="(?P.*)",s*response="(?P.*)",s*opaque="(?P.*)",s*qop=(?P.*),s*nc=(?P.*),s*cnonce="(?P.*)"/' , $_SERVER [ 'PHP_AUTH_DIGEST' ], $digest );
if (!isset( $users [ $digest [ 'username' ]])) 
    die( 'Username not valid!' );
 
// generate the valid response 
$A1 = md5 ( $digest [ 'username' ] . ':' . $realm . ':' . $users [ $digest [ 'username' ]]); 
$A2 = md5 ( $_SERVER [ 'REQUEST_METHOD' ]. ':' . $digest [ 'uri' ]); 
$valid_response = md5 ( $A1 . ':' . $digest [ 'nonce' ]. ':' . $digest [ 'nc' ]. ':' . $digest [ 'cnonce' ]. ':' . $digest [ 'qop' ]. ':' . $A2 );
if ( $digest [ 'response' ] != $valid_response ) 
    die( 'Wrong Credentials!' );
// ok, valid username & password 
echo 'Your are logged in as: ' . $digest [ 'username' ];
?>


兼容性问题:在编写 HTTP 标头代码时请格外小心,为了对所有的客户端保证兼容性,关键字“Basic”的第一个字母必须大写为“B”,分界字符串必须用双引号(不是单引号)引用;并且在标头行 HTTP/1.0 401 中,在 401 前必须有且仅有一个空格.

在以上例子中,仅仅只打印出了 PHP_AUTH_USER 和 PHP_AUTH_PW 的值,但在实际运用中,可能需要对用户名和密码的合法性进行检查,或许进行数据库教程的查询,或许从 dbm 文件中检索.

注意有些 Internet Explorer 浏览器本身有问题。它对标头的顺序显得似乎有点吹毛求疵。目前看来在发送 HTTP/1.0 401 之前先发送 WWW-Authenticate 标头似乎可以解决此问题。

自 PHP 4.3.0 起,为了防止有人通过编写脚本来从用传统外部机制认证的页面上获取密码,当外部认证对特定页面有效,并且 安全模式 被开启时,PHP_AUTH 变量将不会被设置,但无论如何, REMOTE_USER 可以被用来辨认外部认证的用户,因此可以用 $_SERVER['REMOTE_USER'] 变量.

配置说明:PHP 用是否有 AuthType 指令来判断外部认证机制是否有效。

注意,这仍然不能防止有人通过未认证的 URL 来从同一服务器上认证的 URL 上偷取密码.

Netscape Navigator 和 Internet Explorer 浏览器都会在收到 401 的服务端返回信息时清空所有的本地浏览器整个域的 Windows 认证缓存,这能够有效的注销一个用户,并迫使他们重新输入他们的用户名和密码,有些人用这种方法来使登录状态“过期”,或者作为“注销”按钮的响应行为.

例子 34-3.强迫重新输入用户名和密码的 HTTP 认证的范例

复制代码 代码如下:

   function authenticate () { 
     header ( 'WWW-Authenticate: Basic realm="Test Authentication System"' );
     header ( 'HTTP/1.0 401 Unauthorized' ); 
    echo "You must enter a valid login ID and password to access this resourcen" ; 
    exit; 
  }
  if (!isset( $_SERVER [ 'PHP_AUTH_USER' ]) || 
      ( $_POST [ 'SeenBefore' ] == 1 && $_POST [ 'OldAuth' ] == $_SERVER [ 'PHP_AUTH_USER' ])) { 
    authenticate (); 
  } 
  else { 
   echo "

Welcome: { $_SERVER [ 'PHP_AUTH_USER' ]}
" ; 
   echo "Old: { $_REQUEST [ 'OldAuth' ]} " ; 
   echo "

n " ; 
   echo "n" ; 
   echo " n " ; 
   echo "n" ; 
   echo "
n" ; 
  }
?>
该行为对于 HTTP 的 Basic 认证标准来说并不是必须的,因此不能依靠这种方法,对 Lynx 浏览器的测试表明 Lynx 在收到 401 的服务端返回信息时不会清空认证文件,因此只要对认证文件的检查要求没有变化,只要用户点击“后退”按钮,再点击“前进”按钮,其原有资源仍然能够被访问,不过,用户可以通过按“_”键来清空他们的认证信息.

在下例中,我们是使用$PHP_AUTH_USER和$PHP_AUTH_PW这两个变量来验证进入者是否合法并允许进入。在本例中被允许登录的用户名称和密码对分别为tnc和nature:

复制代码 代码如下:

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles