Password Encryption Function


md5() function use to calculate the md5 hash of a given file. The hash is a 32-character hexadecimal number.

Example :
In this example, we learn about how to insert encrypted password while registration and accessing the login page.

DataBase
MySQL mytable table columns id, username, password.
CREATE TABLE mytable
(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
password VARCHAR(50)
);

db.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "password";
$mysql_database = "php_db";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) 
or die("some thing  wrong");
mysql_select_db($mysql_database, $bd) or die("some thing wrong");
?>

registration.php
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']); 
$password=mysql_real_escape_string($_POST['password']); 
$password=md5($password); // Encrypted Password
$sql="Insert into mytable(username,password) values('$username','$password');";
$result=mysql_query($sql);
echo "Registration Successfully";
}
?>
<form action="registration.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />


<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Register "/><br />
</form>

login.php
<?php
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']); 
$password=mysql_real_escape_string($_POST['password']); 
$password=md5($password); // Encrypted Password
$sql="SELECT id FROM mytable WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);

// If result matched $username and $password, table row must be 1 row
if($count==1)
{
echo "welcome ";
}
else 
{
$error="Wrong Login Name or Password ";
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<tr>
     <td><input type="submit" value="login"></td>
     <td><a href="signup.php">New User</td>
</tr>
</form>

Output :