Create a Secure Login Script in PHP (updated)

October 24, 2011 // In: PHP

Security is the basic need/requirement, and it also neccessary for your application to secure your confidentail data/information. Firstly, we need to secure our login pages so that no hacker/unauthorized person can access your applicatin. To secure your authentication, you need to encrypt user password in a way that cannot be decrypted easily. Md5/SHA algorithms can help you in this way.
To create login script, follow the steps..

Step-1
Create user registration form: register.php

<html>
<head>
<title>User Logon</title>
</head>
<body>
<h2>User Login </h2>
<form name="login" method="post" action="user_register.php">
Username: <input type="text" name="txtusername"><br>
Password: <input type="password" name="txtpassword"><br>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>

Step-2
Create page to store user data: user_register.php

Suppose we’ve a database “mydb” that contains “users” table.
“users” table contains two fields username (varchar), password(varchar)

<?php
$con = mysql_connect("localhost", "root", "");
if($con)
{
$select_db = mysql_select_db("mydb", $con);
if(!$select_db)
{
die('Database Error!');
}
}
else
{
die('Connection Error!');
}
$user = mysql_escape_string($_POST['txtusername']);
$pass = mysql_escape_string($_POST['txtpassword']);
//here we encrypt our password
$salt = sha1(md5($pass));
$pass = md5($pass.$salt);
$query_run = mysql_query("Insert Into users values('$user','$pass')", $con);
if($query_run)
{
echo 'Registered Successfully!';
}
else
{
echo 'Not Registered!';
}
?>

Step-3
Create login page: login.php

<html>
<head>
<title>User Logon</title>
</head>
<body>
<h2>User Login </h2>
<form name="login" method="post" action="check_login.php">
Username: <input type="text" name="txtusername"><br>
Password: <input type="password" name="txtpassword"><br>
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>

Preview

Step-4
Create login authentication page: check_login.php


<?php
$con = mysql_connect("localhost", "root", "");
if($con)
{
$select_db = mysql_select_db("mydb", $con);
if(!$select_db)
{
die('Database Error!');
}
}
else
{
die('Connection Error!');
}
$user = mysql_escape_string($_POST['txtusername']);
$pass = mysql_escape_string($_POST['txtpassword']);
//here we encrypt our password in md5 and then we'll compare it..
$salt = sha1(md5($pass));
$pass = md5($pass.$salt);
$query_run = mysql_query("select * from users where username='$user' and password='$pass'", $con);
$rows = mysql_num_rows($query_run);
if($rows)
{
echo 'Login Successfully!';
}
else
{
echo 'Invalid Username/Password!';
}
?>

Note:
You can create different combination/techniques to encrypt password.
For example:
md5(md5(Your Password here));
md5(sha1(md5(Your Password here)));

Object-Oriented PHP for Beginners