PHP anti-SQL injection method Summary and Analysis _php tutorial

Source: Internet
Author: User
In the program development of SQL injection is a common problem that everyone will consider, let me analyze the usual SQL anti-injection code, the need for friends to refer to.

1. The basic principles of PHP submission data filtering

1) When committing variables into the database, we must use Addslashes () to filter, like our injection problem, a addslashes () will be done. In fact, when it comes to variable values, the Intval () function is also a good choice for filtering strings.

2) Open MAGIC_QUOTES_GPC and Magic_quotes_runtime in php.ini. MAGIC_QUOTES_GPC can turn the quotes in the Get,post,cookie into slashes. Magic_quotes_runtime the data in and out of the database can play the role of format. In fact, as early as the previous injection is crazy, this parameter is very popular.

The code is as follows Copy Code

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

Check if the user exists
$t _struname = $_post["F_uname"];
$t _strpwd = $_post["F_pwd"];
$t _strsql = "SELECT * from tbl_users WHERE username= ' $t _struname ' and password = ' $t _strpwd ' LIMIT 0,1 ';

if ($t _hres = mysql_query ($t _strsql))
{
Processing after a successful query. Slightly...
}
}
?>

Sample test



3) When using system functions, you must use the Escapeshellarg (), escapeshellcmd () parameters to filter, so you can rest assured that the use of system functions.

4) for cross-site, Strip_tags (), Htmlspecialchars () Two parameters are good, for the user submitted with HTML and PHP markup will be converted. For example, the angle brackets "<" will be converted to "<" such harmless characters.

The code is as follows Copy Code
$new = Htmlspecialchars ("Test", ent_quotes);
Strip_tags ($text,);

5) for the filtering of related functions, just like the previous include (), Unlink,fopen () and so on, as long as you specify the variables you want to perform the action or filter the relevant characters closely, I think this is also invulnerable.

2, PHP simple data filtering

1) Warehousing: Trim ($STR), Addslashes ($STR)
2) Out of stock: Stripslashes ($STR)
3) Display: Htmlspecialchars (NL2BR ($STR))

I. Types of injection attacks

There may be many different types of attack motives, but at first glance there seems to be more types. This is very real-if a malicious user discovers a way to execute multiple queries. We'll discuss this in more detail later in this article.
Such as
If your script is executing a SELECT directive, an attacker could force the display of each row in a table-by injecting a condition such as "1=1" into the WHERE clause, as shown below (where the injected portion is shown in bold):

The code is as follows Copy Code

SELECT * FROM wines WHERE variety = ' Lagrein ' OR 1=1; '

As we discussed earlier, this may be useful information in itself, as it reveals the general structure of the table (which is not achievable by a common record) and potentially displays records containing confidential information.
An update directive can potentially have a more immediate threat. By placing other attributes in the SET clause, an attacker can modify any field in the record that is currently being updated, such as the following example (where the injected portion is shown in bold):

The code is as follows Copy Code

UPDATE Wines SET type= ' red ', ' vintage ' = ' 9999 ' WHERE variety = ' Lagrein '

By adding a constant condition such as 1=1 to the WHERE clause of an update instruction, the scope of the modification can be extended to each record, such as the following example (where the injected portion is shown in bold):

The code is as follows Copy Code

UPDATE Wines SET type= ' red ', ' vintage ' = ' 9999 WHERE variety = ' Lagrein ' OR 1=1; '

The most dangerous instructions could be delete-. This is not difficult to imagine. The injection technique is the same as we have seen-extending the scope of the affected record by modifying the WHERE clause, such as the following example (where the injected portion is shown in bold):

The code is as follows Copy Code
DELETE from wines WHERE variety = ' Lagrein ' OR 1=1; '

Two, multiple query injection
Multiple query injections will exacerbate the potential damage that an attacker might cause-by allowing multiple destructive instructions to be included in a single query. When using a MySQL database, an attacker could easily do this by inserting an unexpected terminator into the query-an injected quotation mark (single or double quotation marks) marks the end of the desired variable, and then terminates the instruction with a semicolon. Now, an additional attack instruction may be added to the end of the original instruction that is now terminated. The final destructive query might look like the following:
The code is as follows:

The code is as follows Copy Code

SELECT * FROM wines WHERE variety = ' Lagrein ';
GRANT all on * * to ' badguy@% ' identified by ' gotcha '; '

This injection creates a new user Badguy and gives it network privileges (with all the privileges on all tables), and an "ominous" password is added to this simple SELECT statement. If you follow our recommendations in previous articles-strictly restricting the privileges of the process user, this should not work because the Web server daemon no longer has the grant privilege that you withdrew. But in theory, such an attack could give badguy free power to do whatever it does to your database.

Share one of your own writing below

The code is as follows Copy Code

function Phpsql_show ($STR) {
$str = Stripslashes ($STR);
$str = Str_replace ("\", "", $str);
$str = Str_replace ("/", "/", $STR);
$str = Str_replace ("", "" ", $str);
$str = Str_replace (",", ",", $str);
return $str;
}
function Phpsql_post ($STR) {
$str = Stripslashes ($STR);
$str = Str_replace ("|", "|", $STR);
$str = Str_replace ("<", "<", $str);
$str = Str_replace (">", ">", $str);
$str = Str_replace ("", "" ", $str);
$str = Str_replace ("", "" ", $str);
$str = Str_replace ("(", "("), $STR);
$str = Str_replace (")", ")", $str);
$str = Str_replace ("'", "'", $str);
$str = Str_replace ("'", "'", $str);
$str = Str_replace (' "'," "" ", $str);
$str = Str_replace (",", ",", $str);
$str = Str_replace ("$", "$", $str);
$str = Str_replace ("", "\", $STR);
$str = Str_replace ("/", "/", $STR);
return $str;
}
function Phpsql_replace ($STR) {
$str = Stripslashes ($STR);
$str = Str_replace ("'", "'", $str);
return $str;
}


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.

The prevention of SQL injection in DZ is to use the Addslashes function, while there are some substitutions in dthmlspecialchars this function $string = Preg_replace (/& ]{4}));)/, &1, this substitution solves the problem of injection, but also solves some problems of Chinese garbled

http://www.bkjia.com/PHPjc/629645.html www.bkjia.com true http://www.bkjia.com/PHPjc/629645.html techarticle in the program development of SQL injection is a common problem that everyone will consider, let me analyze the usual SQL anti-injection code, the need for friends to refer to. 1. PHP Submit Data ...

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