PHP: Things To Take Note When Writing Login Scripts

Almost every website nowsadays will have some sort of a login system. If you decide to write a login script yourself in PHP, this article will provide some important pointers on the security of the script you are writing. This article will talk on a common login hacking technique known as The SQL Injection Attack. This is not new in the programmer’s world but worth taking note especially when you are new to programming.There are hackers everywhere, so beware! 
When the user submits a form consisting of the username and password, all the variables will be store in the $_POST array after submitting. You can get the values of the array easily using:

$usr = $_POST[‘username’];
$pwd = $_POST[‘password’];

Where “username” and “password” are the names of the textfields in your form.

How do you deal with these values?
You probably verify it against your database. If the username and password matches at least one record in the database, you will let this user proceed on to the secure area, else you will probably throw an error, prompting the user to re-login. During the verification process, your SQL statement might look like this:

SELECT * FROM `user_table`  where username=’$usr’ AND password=’$pwd’

Re-looking at the SQL statement, if someone leaves username empty and writes “ ‘  OR username LIKE ‘%” in the password field, then your whole SQL statement becomes:

SELECT * FROM `user_table`  where username=’ ‘ AND password=’ ‘ OR username LIKE ‘ % ‘

This statement means selecting all the records in the table. If your criteria of letting the user proceed is that the return number of records is more than 0 (at least one user found), then this SQL statement will return all records, meaning that the user will be able to slip pass through the verification process. This type of hacking is famously known as The SQL injection attacks.

One good way to prevent this from happening is to make sure the $_POST array is safe from escape strings such as ‘ and “. You can filter your $_POST array using

$usr = mysql_real_escape_string($_POST[‘username’]);
$pwd = mysql_real_escape_string($_POST[‘password’]);

There are of course other ways to do it but the idea is to let you know that you have to be very careful in handling the data retrieved from forms, epecially more so for usernames and passwords.

Like it.? Share it:

Comments are closed.