db2_escape_string
Prepends backslashes to special characters in the string argument.
Parameters
The string that contains special characters that need to be modified. Characters that are prepended with a backslash are \x00 , \n , \r , \ , ‘ , » and \x1a .
Return Values
Returns string_literal with the special characters noted above prepended with backslashes.
Examples
Example #1 A db2_escape_string() example
Result of using the db2_escape_string() function
$conn = db2_connect ( $database , $user , $password );
if ( $conn ) $str [ 0 ] = «All characters: \x00 , \n , \r , \ , ‘ , \» , \x1a .» ;
$str [ 1 ] = «Backslash (\). Single quote (‘). Double quote (\»)» ;
$str [ 2 ] = «The NULL character \0 must be quoted as well» ;
$str [ 3 ] = «Intersting characters: \x1a , \x00 .» ;
$str [ 4 ] = «Nothing to quote» ;
$str [ 5 ] = 200676 ;
$str [ 6 ] = «» ;
foreach( $str as $string ) echo «db2_escape_string: » . db2_escape_string ( $string ). «\n» ;
>
>
?>
The above example will output:
db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z . db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\") db2_escape_string: The NULL character \0 must be quoted as well db2_escape_string: Intersting characters: \Z , \0 . db2_escape_string: Nothing to quote db2_escape_string: 200676 db2_escape_string:
See Also
mysql_real_escape_string
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
Description
mysql_real_escape_string ( string $unescaped_string , resource $link_identifier = NULL ): string
Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query() . If binary data is to be inserted, this function must be used.
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 (with few exceptions) be used to make data safe before sending a query to MySQL.
Security: the default character set
The character set must be set either at the server level, or with the API function mysql_set_charset() for it to affect mysql_real_escape_string() . See the concepts section on character sets for more information.
Parameters
The string that is to be escaped.
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values
Returns the escaped string, or false on error.
Errors/Exceptions
Executing this function without a MySQL connection present will also emit E_WARNING level PHP errors. Only execute this function with a valid MySQL connection present.
Examples
Example #1 Simple mysql_real_escape_string() example
// Connect
$link = mysql_connect ( ‘mysql_host’ , ‘mysql_user’ , ‘mysql_password’ )
OR die( mysql_error ());
?php
// Query
$query = sprintf ( «SELECT * FROM users WHERE user=’%s’ AND password=’%s'» ,
mysql_real_escape_string ( $user ),
mysql_real_escape_string ( $password ));
?>
Example #2 mysql_real_escape_string() requires a connection example
This example demonstrates what happens if a MySQL connection is not present when calling this function.
// We have not connected to MySQL
?php
$lastname = «O’Reilly» ;
$_lastname = mysql_real_escape_string ( $lastname );
$query = «SELECT * FROM actors WHERE last_name = ‘ $_lastname ‘» ;
var_dump ( $_lastname );
var_dump ( $query );
?>
The above example will output something similar to:
Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5 Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5 bool(false) string(41) "SELECT * FROM actors WHERE last_name = ''"
Example #3 An example SQL Injection Attack
// We didn’t check $_POST[‘password’], it could be anything the user wanted! For example:
$_POST [ ‘username’ ] = ‘aidan’ ;
$_POST [ ‘password’ ] = «‘ OR »='» ;
?php
// Query database to check if there are any matching users
$query = «SELECT * FROM users WHERE user=’ < $_POST [ 'username' ]>‘ AND password=’ < $_POST [ 'password' ]>‘» ;
mysql_query ( $query );
// This means the query sent to MySQL would be:
echo $query ;
?>
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
Notes
Note:
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.
Note:
If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.
Note: mysql_real_escape_string() does not escape % and _ . These are wildcards in MySQL if combined with LIKE , GRANT , or REVOKE .
See Also
User Contributed Notes 10 notes
Just a little function which mimics the original mysql_real_escape_string but which doesn’t need an active mysql connection. Could be implemented as a static function in a database class. Hope it helps someone.
function mysql_escape_mimic ( $inp ) <
if( is_array ( $inp ))
return array_map ( __METHOD__ , $inp );
Note that mysql_real_escape_string doesn’t prepend backslashes to \x00, \n, \r, and and \x1a as mentionned in the documentation, but actually replaces the character with a MySQL acceptable representation for queries (e.g. \n is replaced with the ‘\n’ litteral). (\, ‘, and » are escaped as documented) This doesn’t change how you should use this function, but I think it’s good to know.
No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of «eval» function on.
So, instead of using this terribly broken function, use parametric prepared statements instead.
Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements.
It means instead of building a SQL statement like this:
«INSERT INTO X (A) VALUES(«.$_POST[«a»].»)»
You should use mysqli’s prepare() function (http://php.net/manual/en/mysqli.prepare.php) to execute a statement that looks like this:
NB: This doesn’t mean you should never generate dynamic SQL statements. What it means is that you should never use user-provided data to generate those statements. Any user-provided data should be passed through as parameters to the statement after it has been prepared.
So, for example, if you are building up a little framework and want to do an insert to a table based on the request URI, it’s in your best interest to not take the $_SERVER[‘REQUEST_URI’] value (or any part of it) and directly concatenate that with your query. Instead, you should parse out the portion of the $_SERVER[‘REQUEST_URI’] value that you want, and map that through some kind of function or associative array to a non-user provided value. If the mapping produces no value, you know that something is wrong with the user provided data.
Failing to follow this has been the cause of a number of SQL-injection problems in the Ruby On Rails framework, even though it uses parametric prepared statements. This is how GitHub was hacked at one point. So, no language is immune to this problem. That’s why this is a general best practice and not something specific to PHP and why you should REALLY adopt it.
Also, you should still do some kind of validation of the data provided by users, even when using parametric prepared statements. This is because that user-provided data will often become part of some generated HTML, and you want to ensure that the user provided data isn’t going to cause security problems in the browser.
There is requirement for old projects which are using `mysql_escape_string`, and upgrading the PHP version to 7 and above. Basically this happens in maintenance projects where we don’t know how many files the functions are used in application. We can use [mysqli.real-escape-string][1] for the function:
If you have a typical connection file like `conn.php`
$conn = new mysqli($host, $user, $password, $db);
// may be few more lines to handle the $conn
if (!function_exists(‘mysql_escape_string’)) function mysql_escape_string($sting) < // if mysql_escape_string not available
return $conn->real_escape_string($string); // escape using the $conn instance
>
>
There’s an interesting quirk in the example #2 about SQL injection: AND takes priority over OR, so the injected query actually executes as WHERE (user=’aidan’ AND password=») OR »=», so instead of returning a database record corresponding to an arbitrary username (in this case ‘aidan’), it would actually return ALL database records. In no particular order. So an attacker might be able to log in as any account, but not necessarily with any control over which account it is.
Of course a potential attacker could simply modify their parameters to target specific users of interest:
// E.g. attacker’s values
$_POST [ ‘username’ ] = » ;
$_POST [ ‘password’ ] = «‘ OR user = ‘administrator’ AND » = ‘» ;
// Malformed query
$query = «SELECT * FROM users WHERE user=’ $_POST [ username ] ‘ AND password=’ $_POST [ password ] ‘» ;
// The query sent to MySQL would read:
// SELECT * FROM users WHERE user=» AND password=» OR user=’administrator’ AND »=»;
// which would allow anyone to gain access to the account named ‘administrator’
Don’t forget that if you’re using Mysqli (ie, the «improved» Mysql extension) then you need to use the corresponding mysqli function mysqli_real_escape_string(). The parameter order is also different.
To Quote Sam at Numb Safari
[ «No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of «eval» function on.So, instead of using this terribly broken function, use parametric prepared statements instead.
Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements.» ]
However I do not think it is sensible to stop all sanitising and simply pass the task on to parametric prepared statements.
A particular developer working in a particular situation will always know more about valid input (specific to that context).
If you ask a user to pass in a value you have already given them and you know that all such values start AB****** and the string should be of length 7 or 11 but never any other length then you have the basis of a good pre-sanitiser — different allowable lengths of a string might indicate legacy data.
I would never want to simply pass the rubbish that a malicious user may have passed in through a form to the parametric prepared statements, I would always want to do my own sanity checks first and in some cases these may err on the side of caution and simply choose to abort the Database op completely.
That way my DB does not get clogged up with unsafe statements made safe — it simply does not get clogged up which is better.
Security in layers — sanitisation and validation should still be considered in every situation BEFORE using prepared statements.
In addition as far as I can read into the official doc
==============================================
«Escaping and SQL injection
Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly»
That suggests to me that danger is avoided in the internals by alternative handling not by nullification.
This means that a large project with incomplete conversion to prepared statements, legacy code in different parts of an organisation or servers talking to one another could all pass on the bad news from an immune location or situation to one that is not immune.
As long as the sanitisation is competently performed without incurring additional risks then personally I would stick with certain layers of sanitisation and then call the prepared statements.