PHP secure login

To protect site from dictionary attack or script kiddie you need a special PHP login script. The most important thing is that the value of hidden filed is changing and is random every time you load page login-form.php. So attacker that uses say cURL to attempt brute force attack will use the same value for for hidden filed and change usernames and passwords.
So even if he gets the right both username and password he will be denied of access cause the value of hidden filed is wrong.
First you load login-form.php at this point session variable $_SESSION['rand'] is formed. After entering username and password you are taken to secure-page.php.
In line number 7 we check the value of hidden field. It is different every time for every user but thanks to session we can keep track of right value. In lines 10 and 11 we escape variables to prevent SQL injection attack, in line 12 we check credentials. In production environment we use database to verify users. In line 13 we set cookie to authorize user. That way we can show protected content to the user (line 9) and others get warning message (line 22).

file: login-form.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<title>Login page</title>
<?php 
session_start();
$_SESSION['rand']=mt_rand(1, 10000);
?>
</head>
<body>
<form action="secure-page.php" method="post">
user:<input name="usr" type="text" /><br />
password:<input name="pwd"  type="password" /><br />
<input name="verify" type="hidden" value="<?php echo $_SESSION['rand']; ?>" />
<input name="ok" type="submit" />
</form>
</body>
</html>

file: secure-page.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php 
ob_start();
session_start();
if ($_COOKIE['auth']=='logged_in' ) {
	echo 'protected page';
}
elseif ($_POST['verify']==$_SESSION['rand']) {
	$connect = mysql_connect("localhost", "root", "") or die("bad connection");
	mysql_select_db("some_database");
	$usr=mysql_real_escape_string($_POST['usr']);
	$pwd=mysql_real_escape_string($_POST['pwd']);
	if ( $usr=='mike' && $pwd=='secret' ) { 
		setcookie('auth','logged_in');
		echo 'protected page';
	}
	else {
		echo 'incorrect credentials ';
	}
}
else { 
		echo 'you are not authorized to view this page!'; 
}
ob_end_flush();
?>

Related Posts

  1. Secure data exchange
  2. Prevent SQL injection attack
  3. Test password strength

Leave a Reply

Dansette
SEO Powered by Platinum SEO from Techblissonline