PHP SQL injection and anti-injection classic case Study _php tutorial

Source: Internet
Author: User
Tags how to prevent sql injection how to prevent sql injection attacks simple sql injection sql injection attack sql injection methods
For SQL injection and anti-injection is actually an attack and defense, today we want to tell you the most basic injection and prevention methods, the principle is to take advantage of some PHP or MySQL features and we did not pay attention to the cause.

A simple SQL injection attack case
If we have a company website, we store all the important information such as customer data in the background database of the website. If there is a command in the code of the website login page to read the user information.

The code is as follows Copy Code

$q = "Select ' id ' from ' users ' WHERE ' username ' = '". $_get[' username ']. " ' and ' password ' = ' ". $_get[' password ']." ' ";

?>

Now that a hacker wants to attack your database, he will try to enter the following code into the user name input box on this login page:

The code is as follows Copy Code

' ; SHOW TABLES;

Click the login button, this page will show all the tables in the database. If he now uses the following line of command:

The code is as follows Copy Code

'; DROP table [table name];

So he's got a watch removed!

Of course, this is a very simple example, the actual SQL injection method is much more complex than this, hackers are willing to spend a lot of time to constantly try to attack your code. Some program software can also automatically try to keep trying SQL injection attacks. After understanding the attack principle of SQL injection, let's look at how to prevent SQL injection attacks.

MAGIC_QUOTES_GPC = injection attack at On
When MAGIC_QUOTES_GPC = ON, an attacker cannot inject SQL into a character-type field. That doesn't mean it's safe. In this case, SQL injection can be done with numeric fields.

In the latest version of MYSQL 5.x, data type input has been strictly, and automatic type conversion has been turned off by default. Numeric field, cannot be a character type of quotation marks. That is, assuming the UID is numeric, in the previous MySQL version, such statements are legal:

The code is as follows Copy Code

INSERT into Tbl_user SET uid= "1";
SELECT * from Tbl_user WHERE uid= "1";

In the latest MYSQL 5.x, the above statement is not legal and must be written like this:

The code is as follows Copy Code

INSERT into Tbl_user SET uid=1;
SELECT * from Tbl_user WHERE uid=1;

So I think it's right. Because as a developer, it is the most basic requirement to submit the correct rules-compliant data types to the database.

So how do attackers attack when MAGIC_QUOTES_GPC = on? It's easy to do SQL injection on numeric fields. Take the following PHP script as an example:

The code is as follows Copy Code

if (Isset ($_post["F_login"))
{
Connect to Database ...
// ... Code slightly ...

Check if the user exists
$t _struid = $_post["F_uid"];
$t _strpwd = $_post["F_pwd"];
$t _strsql = "SELECT * from Tbl_users WHERE uid= $t _struid and password = ' $t _strpwd ' LIMIT 0,1 ';
if ($t _hres = mysql_query ($t _strsql))
{
Processing after a successful query. Slightly...
}

}
?>
Sample test



The above script requires users to enter UserID and password login. A normal statement, the user enters 1001 and abc123, commits the SQL statement as follows:

The code is as follows Copy Code
SELECT * from tbl_users WHERE userid=1001 and password = ' abc123 ' LIMIT 0,1

If the attacker is at the UserID, enter: 1001 OR 1 = 1 #, the SQL statement injected is as follows:

The code is as follows Copy Code
SELECT * from Tbl_users WHERE userid=1001 OR 1 =1 # and password = ' abc123 ' LIMIT 0,1

The attackers achieved their purpose.

Prevent SQL injection-using the mysql_real_escape_string () function

In the code of the database operation, the function mysql_real_escape_string () can filter out special characters in the code, such as quotation marks. The following example:

The code is as follows Copy Code

$q = "Select ' id ' from ' users ' WHERE ' username ' = '". Mysql_real_escape_string ($_get[' username ']). " ' and ' password ' = ' ". Mysql_real_escape_string ($_get[' password '])." ' ";

?>

Prevent SQL injection-using the mysql_query () function

mysql_query () in particular, it will only execute the first of the SQL code, and the latter will not be executed. Recall in the first example, the hacker through the code to execute several SQL commands in the background, showing the names of all the tables. So the mysql_query () function can take the role of further protection. We further evolved the code just now to get the following code:

copy code

"!--?

//connection
$database = mysql_connect ("localhost", "username", "password");

//db selection
mysql_select_db ("database", $database);

$q = mysql_query ("Select ' id ' from ' users ' WHERE ' username ' = '". Mysql_real_escape_string ($_get[' username ']). " ' and ' password ' = ' ". Mysql_real_escape_string ($_get[' password '])." ' ", $database);

?

In addition, we can determine the length of the input value in PHP code, or use a function to check the input value. Therefore, in accepting the user input value of the place must be good to filter and check the input content. Of course, learning and understanding the latest SQL injection methods is also very important, so as to achieve a purposeful defense. If you are using a platform-style website system such as WordPress, be careful to make an official patch or upgrade to a new version in time. If there is a wrong place or do not understand, please leave a comment in the comments section.

The display_errors option in php.ini should be set to Display_errors = off. In this way, the PHP script does not output errors in the Web page after the error, so that the attacker could parse out the information.
When you call a MySQL function such as mysql_query, you should precede it with @, which is @mysql_query (...) so that the MySQL error is not output. In the same vein, the attacker is not allowed to parse out useful information. In addition, some programmers in the development, when mysql_query error, used to output errors and SQL statements, such as:

The code is as follows Copy Code
$t _strsql = "Select a from B ...";
if (mysql_query ($t _strsql))
{
The right treatment
}
Else
{
echo "Error! SQL statement: $t _strsql RN error message ". mysql_query ();
Exit
}

This practice is quite dangerous and foolish. If you must do this, it is best to set a global variable or define a macro in the configuration file of the Web site, and set the debug flag:

In the global configuration file:

The code is as follows Copy Code
Define ("Debug_mode", 0); 1:debug MODE; 0:release MODE

In the call script:

The code is as follows Copy Code
$t _strsql = "Select a from B ...";
if (mysql_query ($t _strsql))
{
The right treatment
}
Else
{
if (Debug_mode)
echo "Error! SQL statement: $t _strsql RN error message ". mysql_query ();
Exit
}


About SQL anti-injection content http://www.bKjia.c0m/phper/phpanqn/37704.htm

http://www.bkjia.com/PHPjc/629669.html www.bkjia.com true http://www.bkjia.com/PHPjc/629669.html techarticle for SQL injection and anti-injection is actually an attack and defense, today we want to tell you the most basic injection and prevention methods, the principle is to take advantage of PHP or MySQL some features and we did not note ...

  • 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.