简体   繁体   中英

PHP header authentication strange code

I copied from PHP.net code for header authentication

Here is the code:

<?php
$valid_passwords = array ("Itay" => "1234", "beta" => "password");
$valid_users = array_keys($valid_passwords);
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];
$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);
if (!$validated) {
  header('WWW-Authenticate: Basic realm="this is testing area. beta testers only!"');
  header('HTTP/1.0 401 Unauthorized');
  die ("Not authorized");
}
// If arrives here, is a valid user.
?>

Now, my question is why does this line:

$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);

is used instead of

$validated = $pass == $valid_passwords[$user];

$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);

This row check both that user exists and password is correct.

if you remove user check, then user ="nonexisting" and password= "" will be valid (and of course, there will be notice.

check:

$pass = "";
$user = "any non existing"
$validated = ($pass == $valid_passwords[$user]); //here will be notice
var_dump($validated);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM