Encrypting Password in PHP

Encrypting Password in PHP

In this simple tutorial we will be encrypting password in PHP. If you are developing a password-protected web site, you have to make a decision about how to store user password information securely.

What is “secure,” anyway? Realize that the data in your database is not safe. What if the password to the database is compromised? Then your entire user password database will be compromised as well. Even if you are quite certain of the security of your database, your users’ passwords are still accessible to all administrators who work at the web hosting company where your database is hosted. Scrambling the passwords using some home-brewed algorithm may add some obscurity but not true “security.” Another approach would be to encrypt all passwords in your database using some industry-standard cipher, such as the Message-Digest Algorithm 5 (MD5).

When you encrypt “john123” using this code, you’ll see the result “6e0b7076126a29d5dfcbd54835387b7b”

This is not a random result, everytime you encrypt the same password you will get the same result.

Example – Encrypting Password


$password = "john123";
$encrypted_password = md5($password);

echo $encrypted_password; 

Alternative to MD5

You can also use sha1() functoin which is considered to be a bit more secured than md5 because md5 can be easily decrypted using passowrds databases if password is not strong.


$password = "john123";
$encrypted_password = sha1($password);

echo $encrypted_password; 

Example – Login

This is an example Login with encrypted password, but don’t forget to encrypt password and insert into database when your user sign up.


// username and password sent from form
$username = $_POST['username'];
$password = $_POST['password'];

// encrypt password
$encrypted_password = md5($password);

$result = mysql_query("SELECT * FROM `table_name` WHERE username = '$username' and password='$encrypted_password'");

To learn more about md5() and sha1, please check out the functions below.

Functions Used: