Creating Secure Login in PHP

April 15, 2006 {2 years, 6 months ago.} (posted by Anish Blon)

This articles demonstrate and explains how to create a secure PHP login script that will allow safe authentication. Here, cookies are not used because of preventive measure against cross-side scripting. The back-end used is MySQL. So, you should have knowledge of MySQL and database as well.

Database Schema

For example lets make a table called login for this tutorial purpose only. For commercial purpose, please do add relevant attributes in the table. Use SQL below to create a table of login.

1
2
3
4
5
CREATE TABLE login (
user_name VARCHAR(20) NOT NULL DEFAULT '',
user_pass CHAR(32) BINARY NOT NULL DEFAULT '',
PRIMARY KEY (username)
);

Creating a HTML Form

1
2
3
4
5
<form method="post" action="login.php" name="login">
<input name="user_name" size="18" type="text" />
<input name="user_pass" size="18" type="text" />
<input name="submit" value="Login" type="submit" />
</form>

Handling Form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if(count($_POST) &gt; 0) {
 $user_name = htmlspecialchars($_POST["user_name"]);
 $user_pass = htmlspecialchars($_POST["user_pass"]);
 
 $sql = "SELECT user_name,user_pass FROM login
           WHERE user_name=\"$user_name\"
            AND    user_pass=\"$user_pass\"";
 
 $rs = mysql_query($sql);               //execute the query
 if(mysql_num_rows($rs)	==	1)  {
 	// username and passwords exists in database
       //other codes
 }
 else {
 	//invalid username of password
 	//redirect to login page
 
 	header("Location: login.php");
 }
 
}

Above is fairly a simple login page. We can add many other functionalities.


Recommended Reading


Post a comment or question



  1. (required)(required)

  2. (required)(required)(will not be published)


Search on site