Securing passwords
15
This litle snippet shows how to store passwords and then check inputed passwords if they are correct.
(In this snippet we use som pseduo code for the database connection).
(In this snippet we use som pseduo code for the database connection).
// First we connect to the database
db::connect('localhost', 'root', '', 'testDatabase');
// Input is the following:
// $_POST['username'] containing the specified username.
// $_POST['password'] cointainging the specified password.
// The first thing you always do with data which comes from the use
// is to sanitize it (never trust the user).
// The function db::escape() is a pseudo function for functions such as
// mysql_real_escape_string() and other like it or in worst case just for
// addslashes()
$_POST['username'] = db::escape($_POST['username']);
// Never store passwords unless you have encrypted them first!
// Think about this situation, your database gets hacked and the hackers
// manages to retrieve your whole user table. What do you think they
// might do then? Login as a user (possible with the highest rank, admin)
// and play around. But if you store the password in an encrypted form,
// they have no chanse to do this.
$_POST['password'] = sha1($_POST['password']);
// Now let's execute a query to se if we have a match
$result = db::query("SELECT `userID` FROM `users` WHERE `username` = '".$_POST['username']."' AND `password` = '".$_POST['password']."'");
// Did any rows match?
if (db::numRows($result) == 0)
// No rows matched, send the user a error message
echo 'The username you enetered doesn\'t exists or the password supplied with the username is incorrect, please try again.';
else
// The query matched a username with the specified password =D
echo 'Woho, you are one of us! Here are the top secret documents..';





There are easily accessed databases of md5 and sha1 hashes of passwords to allow the dumped databased to be quickly scanned. Simply using a salt will be a huge improvement.