PHP Analog HTTP Basic authentication (Basic authentication)

Source: Internet
Author: User

When a page requires authentication for access, it can send a response that contains the Www-authenticate header (used to identify the authentication security domain), and the HTTP status code for the response is 401;

When the browser sees a 401 header, a dialog box pops up asking for a user name and password. If the user enters a user name and password, the user name and password entered by the user will be saved separately to $_server[' Php_auth_user ' and $_server[' PHP_AUTH_PW '], Developers can design programs to verify that the user name and password entered are correct.

Code:

1<?PHP2 3 Header("content-type:text/html; Charset=utf-8 ");4 5 functionValidate$user,$pass) {6     $users= [' Dee ' = ' 123456 ', ' admin ' = ' admin '];7     if(isset($users[$user]) &&$users[$user] ===$pass) {8         return true;9}Else {Ten         return false; One     } A } -  - if(!validate (@$_server[' Php_auth_user '], @$_server[' PHP_AUTH_PW '])) { theHttp_response_code (401); -     Header(' Www-authenticate:basic realm= ' My website ');//The dialog box displays the http://127.0.0.3 request user name and password. Information is: My website -     Echo' Require user name and password to continue access ';//Cancel when browser output -     Exit; +}Else { -     Var_dump($_server[' Php_auth_user ']); +     Var_dump($_server[' PHP_AUTH_PW ']); A}

When you visit the page, the authentication window pops up:

When you select Cancel:

When you output the correct user name and password:

Reference: "PHP cookbook,3rd" P244

PHP Analog HTTP Basic authentication (Basic authentication)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.