mysql_real_escape_string() calls MySQL’s library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ‘, ” and \x1a.
This function must always be used to make data safe before sending a query to MySQL.
A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn’t defined, the last MySQL connection is used.
Using mysql_real_escape_string() in php we can prevent database attacks ,a small example shown below
<?php function safe($value) { global $conn; return mysql_real_escape_string($conn,$value); } // safe sql $firstname = safe($_POST['firstname']); $lastname = safe($_POST['lastname']); $username = safe($_POST[username]); $password = safe($_POST[password]); $sql=”select * from table_name where username=$username and password=$password”; Mysql_query($sql); Mysql_close($conn); ?>
What could be happen if we are not using mysql_real_escape_string() function on the username and password:
<?php $conn= mysql_connect("localhost", "joseph", "joseph123"); if (!$conn) { die('Could not connect: ' . mysql_error()); } $result= "select * from table_name Where username='{$_POST[username]}' And password='{$_POST['password']}'"; mysql_query($result); // Could be anything the user wanted! Example: $_POST[username] = 'joseph'; $_POST[password] = "' OR ''='"; // some code mysql_close($conn); ?> The SQL sent would be: SELECT * FROM username Where username='joseph' AND password='' OR ''=''
This means that anyone could log in without a valid password!
To prevent these attacks use mysql_real_ escape_string() function.
Advantages:
• mysql_real_escape_string() is necessary to control what the users are storing in the database and to prevent sql injection.
• mysql_real_escape_string ensures that whatever the user enters is processed first before it is stored in the database and characters with special meaning to the sql engine is properly escaped.
Leave A Comment