Friday, January 29, 2010

MySQLI_Real_Escape_String()---A Useful Function

If you are collecting information through an html form or providing user access to a MySQL database, the mysqli_real_escape_string() function can be a very useful tool to employ. This function can be used to prevent database attacks from malicious users by "escaping" special characters such as "\r,"\n",!\,etc.

Situations where such special characters cause problems are usernames and passwords. The code below shows an example of what could happen.

// We didn't check username and password.
// Could be anything the user wanted! Example:
$_POST['user'] = 'jerry';
$_POST['pwd'] = "' OR ''='";

The SQL sent would be:
SELECT * FROM users
WHERE user='jerry' AND password='' OR ''=''
This means that anyone could log in without a valid password!

To prevent this, you "escape" special characters with the mysqli_real_escape_string() function, which takes two arguments, the database connection variable and the string variable to be escaped. The function returns a string on success or FALSE for failure. Depicted below is the syntax:

$string=mysqli_real_escape_string($dbc,$escapeString)--where $dbc is the database link connection and $escapeString is the string to be escaped.

Using the Post method, the username and password would be "escaped" like this:

$user=mysqli_real_escape_string($dbc,$_POST['user']);
$pwd=mysqli_real_escap_string($dbc,$_POST['pwd']);

No comments:

Post a Comment

Get your own Widget