Home > Backend Development > PHP Tutorial > Detailed explanation of the code for php to implement web security authentication

Detailed explanation of the code for php to implement web security authentication

黄舟
Release: 2023-03-16 13:26:02
Original
1996 people have browsed it

This article mainly introduces the relevant information of detailed examples of PHP web security authentication. Here are two implementation methods, one is based on the database and the other is not based on the database. I hope it can help everyone through instinct. If you need it, Friends can refer to the detailed explanation of

PHP web page security authentication examples

Not based on database:


##

<?php
    //unset($_SERVER[&#39;PHP_AUTH_USER&#39;]);
    $strAuthUser= $_SERVER[&#39;PHP_AUTH_USER&#39;];      
    $strAuthPass= $_SERVER[&#39;PHP_AUTH_PW&#39;];

 if (! ($strAuthUser == "a" && $strAuthPass == "a")) {
  header(&#39;WWW-Authenticate: Basic realm="wly"&#39;);
  header(&#39;HTTP/1.0 401 Unauthorized&#39;);
  echo "用户验证!!";
  exit;
 } else {
  echo "验证通过";
  
  header("location:http://www.baidu.com");
  //unset($_SERVER[&#39;PHP_AUTH_USER&#39;]);  
 }
?>
Copy after login

Based on database:



<?php
  function authenticate_user() {
    header(&#39;WWW-Authenticate: Basic realm="Secret Stash"&#39;);
   header("HTTP/1.0 401 Unauthorized");
    exit;
  }
 
  if (! isset($_SERVER[&#39;PHP_AUTH_USER&#39;])) {
    authenticate_user();
  } else {
    mysql_pconnect("localhost","authenticator","secret") or die("Can&#39;t connect to database server!");
    mysql_select_db("java2s") or die("Can&#39;t select authentication database!");
 
   $query = "SELECT username, pswd FROM user WHERE username=&#39;$_SERVER[PHP_AUTH_USER]&#39; AND pswd=MD5(&#39;$_SERVER[PHP_AUTH_PW]&#39;)";
 
    $result = mysql_query($query);
 
    // If nothing was found, reprompt the user for the login information.
    if (mysql_num_rows($result) == 0) {
     authenticate_user();
    }
  }
 ?>
Copy after login

The above is the detailed content of Detailed explanation of the code for php to implement web security authentication. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template