Saturday, December 22, 2012

Using Encrypted Passwords in PHP Login Script


Suppose someone breaches into our database, he can easily get the users ‘username’ and ‘passwords’. To avoid this situation we use encrypted passwords.

Even if someone enters into our database, he cannot get the password. When a user wants to login, his password is converted into the same format and matched with the database encrypted password. If both usernames and encrypted passwords match, then user will be logged in.

Usually, md5() function is used to encrypt the passwords. It generates a 32 characters word. Following code of PHP Login System shows the implementation of the function.

Database Table of users

Id
user
pass
1
userone
b7e055c6165da55c3e12c49ae5207455
2
usertwo
c4d8a57e2ca5dc5d71d2cf3dbbbbaabe

After submitting the login credentials, the following script will handle the login request.               

$user=$_POST['user'];
$pass=md5($_POST['pass']); //This is the only change

//checks if a user exists in database having `user` and `pass` equal to $user and $pass respectively.
$chkqry=mysql_query("select `id` from `users` where `user`='".$user."' and `pass`='".$pass."'");

//if user exists then, set cookie `SessionId` and redirect to home.php page
if(mysql_num_rows($chkqry)>0) {
      setcookie("SessionId",$user,0);
      header('location:home.php');
}

//if user doesn’t exist then, shows message ‘Incorrect Username or Password’ on login.php page
     else {
           header('location:login.php?msg=Incorrect Username or Password');
     }


No comments:

Post a Comment