Securing passwords





15
Date Submitted Thu. Jul. 27th, 2006 7:21 AM
Revision 1 of 1
Helper rastersize
Tags login | Password | PHP | Security
Comments 1 comments
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).

// 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..';
 

Aron C

jiart.org/
-----------------------
http://jiart.org/
My digital playground with it's own sandbox.
Well anyway, I love programming

Comments

Comments SQL injection on userid
Mon. Oct. 9th, 2006 8:25 AM    Beginner rdivilbiss

Voting