PHP mysql_real_escape_string () function anti-SQL injection

Source: Internet
Author: User
Tags mysql functions php mysql vars

PHP MySQL functions

Definition and usage

The mysql_real_escape_string () function escapes special characters in strings used in SQL statements.

The following characters are affected:

    • \x00
    • \ n
    • \ r
    • \
    • "
    • \x1a

If successful, the function returns the escaped string. If it fails, it returns false.

Grammar
Mysql_real_escape_string (string,connection)
Parameters Description
String Necessary. Specifies the string to be escaped.
Connection Optional. Specify MySQL connection. If not specified, the previous connection is used.
Description

This function escapes the special characters in the string and takes into account the current character set of the connection, so it can be used safely for mysql_query ().

Hints and Notes

Tip: You can use this function to prevent database attacks.

Example Example 1
<?php$con = mysql_connect ("localhost", "Hello", "321"), if (! $con)  {die  (' Could not connect: '. Mysql_error () );  mysql_real_escape_string($user)mysql_real_escape_string($pwd); $sql = "SELECT * from Users whereuser= '". $user. "' and password= '". $pwd. "'"//More Code mysql_close ($con);? >
Example 2

Database attacks. This example shows what happens if we do not apply the mysql_real_escape_string () function to the username and password:

<?php$con = mysql_connect ("localhost", "Hello", "321"), if (! $con)  {die  (' Could not connect: '. Mysql_error () );  } $sql = "SELECT * from Userswhere user= ' {$_post[' user '} ' and password= ' {$_post[' pwd '} '"; mysql_query ($sql);//Do not check username and password Can be any user input, such as: $_post[' user '] = ' john '; $_post[' pwd '] = ' OR ' = ' ";//Some code ... mysql_close ($con);? >

Then the SQL query will be like this:

SELECT * from Userswhere user= ' John ' and password= ' OR ' = '

This means that any user can log in without entering a valid password.

Example 3

The right way to prevent database attacks:

<?phpfunction Check_input ($value) {//Strip Slash if (GET_MAGIC_QUOTES_GPC ())  {  stripslashes($value) ;  } If it is not a number, quote if (!is_numeric ($value))  {  mysql_real_escape_string($value) . "'";  } return $value;} $con = mysql_connect ("localhost", "Hello", "321"), if (! $con)  {die  (' Could not connect: '. Mysql_error ());  } Secure Sql$user = check_input ($_post[' user "), $pwd = Check_input ($_post[' pwd '); $sql =" SELECT * from Users whereuser= $u Ser and password= $pwd "; mysql_query ($sql); Mysql_close ($con);? >
//----------------------------------------------

I've never really been concerned about this before. I used a very simple function when I wrote it.

PHP code
  1. <?php
  2. function Escape ($str) {
  3. if (function_exists (' mysql_escape_string ')) {
  4. return mysql_escape_string ($str);
  5. }ElseIf (Function_exists (...)) {  
  6. //real_escape
  7. }else{
  8. if (Magic_quoter .... Judgment) {
  9. return $str
  10. }else{
  11. return addslashes ($str);
  12. }
  13. }
  14. }

But this article tells me that the original functions of the three functions are different, the first two of course I know, but if not loaded MySQL library, these two features are not used, of course, now have PDO prepare and then SetParam is certainly very convenient, mysqli function also has this function. What if not? What to do? The following article tells you the difference between the above three functions
Source: Http://www.akii.org/2009-08/php-in-the-addslashes-mysql_real_escape_string-and-mysql_escape_ string-the-difference-between/

SQL injection attacks are the most common means by which hackers attack websites. If your site does not use strict user input validation, it is often vulnerable to SQL injection attacks. SQL injection attacks are typically implemented by submitting bad data or query statements to the site database, which is likely to expose, change, or delete records in the database.

In order to prevent SQL injection attacks, PHP comes with a function to process the input string, the input can be in the lower level of security preliminary processing, also known as Magic Quotes. (PHP.ini MAGIC_QUOTES_GPC). If the MAGIC_QUOTES_GPC option is enabled, then the single quotation marks, double quotes, and some other characters in the input string will be automatically preceded by a backslash \.

But Magic quotes is not a very general solution, it does not block all potentially dangerous characters, and magic quotes is not enabled on many servers. So there are a number of other ways we need to prevent SQL injection.

Many databases themselves provide this input data processing capability. For example, PHP's MySQL operator function has functions such as addslashes (), mysql_real_escape_string (), mysql_escape_string (), which can escape special characters and characters that may cause errors in database operations. So what's the difference between these three function functions? Let's go over the details below.

Although many PHP programmers in the country still rely on addslashes to prevent SQL injection, it is recommended to strengthen Chinese to prevent SQL injection check. The problem with addslashes is that hackers can use 0xbf27 instead of single quotes, and addslashes just modifies 0xbf27 to 0xbf5c27 as a valid multibyte character, where 0xbf5c is still considered a single quote, So addslashes can't intercept successfully.

Of course addslashes is not useless, it is used for single-byte string processing, multibyte characters or mysql_real_escape_string bar.

Another example of GET_MAGIC_QUOTES_GPC in the PHP manual:
if (!GET_MAGIC_QUOTES_GPC ()) {
$lastname = addslashes ($_post[' LastName ');
} else {
$lastname = $_post[' LastName ');
}
It is best to check the $_post[' LastName ' If the MAGIC_QUOTES_GPC is already open.

Again, the difference between the 2 functions of mysql_real_escape_string and mysql_escape_string:
Mysql_real_escape_string must be used in cases (PHP 4 >= 4.3.0, PHP 5). Otherwise you can only use mysql_escape_string, the difference between the two is: Mysql_real_escape_string consider the current character set of the connection, and mysql_escape_string not consider.

To summarize:

* Addslashes () is forcibly added \;
* Mysql_real_escape_string () will determine the character set, but the PHP version is required;
* Mysql_escape_string does not consider the current character set of the connection.

PHP mysql_real_escape_string () function anti-SQL injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.