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)