Now that we have these valid users and their passwords (a.k.a last names), we can use the array_key_exists() function and simple comparators to check if we the submitted information is valid.
<?php // login.php $validUsers = array("peter"=>"pan", "john"=>"smith", "robert"=>"scoble"); print $_POST['user']; if(array_key_exists($_POST['user'], $validUsers)) { $user = $_POST['user']; print "<br/>".$validUsers["$user"]; } else print "<br/>No matches found."; ?>
If your submitted information matches a username, it prints out the password. If not it tells you so. Now we are at the point where we can use use the password to make the final decision about whether to admit access or not. Here’s the rest of it.
<?php // login.php $validUsers = array("peter"=>"pan", "john"=>"smith", "robert"=>"scoble"); if(array_key_exists($_POST['user'], $validUsers)) { $user = $_POST['user']; if($validUsers["$user"] == $_POST['pass']) { print "This is the protected information."; } else { print "Sorry, the password you supplied doesn't match up."; exit(); } } else { print "The username ".$validUsers["$user"]." was not found."; exit(); } ?>
There you have it, the absolute essentials of form handling and a minor example of password protection.
Posted October 2nd, 2006 - Permalink