You should never save passwords as is to the database because somebody could gain access to the database (via security hole, etc.) and download all the passwords.
Best approach would be to encrypt passwords before saving to the database.
Process would work as follows:
1. User signs up to your site, providing
login and
password2. You
save login as is, and
encrypt password before saving to the database. Usually
md5 function is utilized for this.
md5 function always produces 32 characters length string, so make sure your password field in the database can fit it.
Example: $encrypted_password = md5($password);
3. User login to your site next time, providing login and password.
4. You validate like this:
- compare login with the login stored in the database
- make md5 from the password provided in login form, and compare it with encrypted value stored in database.
5. Now user forgot his password, and wants you to send it via email. We are unable to retrieve user's password since we only have encrypted password.
So instead of sending old password we should:
- send a link to the "new password" form, where user would select new password
OR
- auto-generate new password for the user, send not encrypted password via email, and save encrypted password to the database
You might noticed a lot of sites would never send you old password when you use password reminder. These sites are following above protection approach, where nobody knows user's password (even site admins).
Now nobody will be able to get passwords, even if one gets unauthorized access to the passwords database. They will only see encrypted passwords.
Simple login code example.
// login / password from the login form
$login = $_POST['login'];
$password = $_POST['password'];
// encrypted password from the login form
$encrypted_password = md5($password);
//////////////////////////////////////////////////////////////////////////////
// here will be your custom code to retrieve user's password from the database
// something like:
// $elogin = mysql_escape_string($login);
// mysql_query("select user_password from users where user_login = '$elogin'");
//////////////////////////////////////////////////////////////////////////////
if ($encrypted_password == $user_password_from_db) {
// password is ok
}
else {
// wrong password
}