Also talk about the prevention of PHP program SQL Injection

Source: Internet
Author: User
Tags valid email address

Text/graph non-zero solution & Zhou Lin
Currently, PHP security has become a hot topic in the PHP field. To ensure that scripts are safe, you must start with the most basic-input filtering and secure output. If you do not fully perform these basic tasks, your scripts will always have security issues. This article will discuss the prevention of SQL Injection for PHP programs from input filtering.
 
Prevention of injection of volume type
When the input of the script comes from other places, the input must be insecure. Common dangerous scripts include $ _ POST, $ _ GET, $ _ REQUEST, and $ _ SERVER. These are seemingly safe, and there are actually some dangerous risks. In the face of these external scripts, the first thing you need to do before doing further work is to make it legal and filter it effectively. Make sure that the script contains what you need. Just like if you want to apply for an email address, you only need to make sure it is a valid email address. The following is an example.
 
<? Php
$ Email = $ _ POST [email]; # security problems exist here
// Determine whether the email is valid
If (valid_email ($ email) = false ){
// Not a limited email address
Die (Invalid E-mail Address !);
}
?>

By checking this data, we should try our best to reject writing dangerous data into the script. Even if we can determine that the data is safe, it does not mean that the work is complete. We also need to make sure it is safe when it is inserted. PHP has a standard function-mysql_real_escape_string (), which is a special character in the character string used in the escape SQL statement.
 
Knowledge
Mysql_real_escape_string () is a special character in the character string used in the escape SQL statement, and takes into account the connected current character set. Usage: string mysql_real_escape_string (string unescaped_string [, resource link_identifier]), the function is to escape special characters in unescaped_string and calculate the connected current character set. Therefore, it can be safely used for mysql_query (), mysql_real_escape_string () without escaping "%" and "_".
 
Therefore, in the above example, we can convert it into the following form.
 
<? Php
$ Email = $ _ POST [email];
If (valid_email ($ email) = false ){
Die (Invalid E-mail Address !);
}
$ Email = mysql_real_escape_string ($ email );
?>

Now the data is completely secure and can be inserted into the database with confidence. To avoid errors and increase the readability of the code, we usually add a prefix to it.
 
<? Php
$ D_Email = $ _ POST [email];
$ S_Email = mysql_real_escape_string ($ d_Email );
?>
 
In this way, it always appears with a fixed prefix "d. When you insert a dangerous data, you will immediately realize this, which is a good coding habit.
Of course, in php. when magic_quotes_gpc = On in ini, all the "" (single quotation marks), "" (double quotation marks) and "" (backslash) in the submitted variables can also be used) and empty characters are automatically converted into escape characters containing backslash, such settings may not be conducive to the development of the entire program. You can also use mysql_escape_string () to escape non-numeric data submitted by the user (similar to mysql_real_escape_string ). If only letters and numbers are allowed in a string, you can use the ctype_alnum () function ().
 
Knowledge
Ctype_alnum () is used to check whether a string contains only letters and numbers. It is used as Bool ctype_alnum (string unescaped_string );. If the unescaped_string contains only letters or numbers, this function returns True.
 
Protection against Digital Injection
The above filter can prevent numeric injection. For numeric injection, we can use other functions to check or process submitted data. The following SQL statement is used as an example to describe SQL injection.
 
$ Userid = $ _ POST [userid];
$ Query = "SELECT * FROM users WHERE id = $ userid ";
 
Here, userid accepts numbers. You can use functions such as is_int (), is_integer (), is_long (), is_numeric (), and ctype_digit () to determine whether the accepted data is a number.
 
Knowledge
1. is_int () function (alias function is_integer () or is_long (), which is used as bool is_int (mixed var ). If var is an integer, TRUE is returned; otherwise, FALSE is returned.
2. is_numeric () function, which is used as bool is_numeric (mixed $ var ). If the variable is a number or a string that contains numbers and symbols, decimal points, and indexes, this function returns True.
3. ctype_digit () function. Its usage is ctype_digit ($ string ). If the string contains only the characters "0" to "9", the function returns True. Note that decimal points are not allowed.
 
After the previous example is processed by the above function is_numeric (), we convert it to the following:
 
If (is_numeric ($ _ POST [userid])
$ S_userid = $ _ POST [userid];
$ Query = "SELECT * FROM users WHERE id = $ s_userid ";
 
The s_userid above indicates that the data is secure and increases the readability of the Code (although I often forget this when writing a program, it is recommended ). In this way, the function that determines the number effectively checks the input data. We can also use the settype () and intval () functions in the program to convert the input data into numbers.
The settype () function can be used to process the input data.
 
$ D_userid = $ _ POST [userid];
If (settype ($ d_userid, integer ))
$ S_userid = $ d_userid
$ Query = "SELECT * FROM users WHERE id = $ s_userid ";
 
Knowledge
1. intval () function, used as int intval (mixed $ var [, int $ base]). Return the value of the variable var by using a specific hexadecimal conversion (default decimal. Var can be any scalar type. Intval () cannot be used for array or object. Note that the base parameter of intval () does not work unless the var parameter is a string.
2. settype () function. Its usage is bool settype (mixed $ var, string $ type ). Set the var variable type to type. The possible value of type is "boolean" (or "bool", PHP 4.2.0 or above), "integer" (or "int", PHP 4.2.0 or above), "float" (only available after PHP 4.2.0, "double" used in the old version is disabled now). If it succeeds, TRUE is returned. If it fails, FALSE is returned.
 
Compile a function to filter input
PHP functions strictly filter input, but many problems may occur when writing code. For example, we must consider the function used to filter each variable. This creates a secure abstraction layer that can automatically filter input, you can create a filter method in a function or encapsulate it in a class.
In PHP, two common functions are used to filter input of the struct type: addslashes () and mysql_real_escape_string (). These two functions are applicable to different PHP versions. They are used only when mysql_real_escape_string () is PHP> = 4.3.0. For PHP + MYSQL programs, if we do not know the PHP version used by users, we can write functions for corresponding judgment.
 
Function SQL _quote ($ value ){
// Determine whether get_magic_quotes_gpc is on and remove the backslash character.
If (get_magic_quotes_gpc ()){
$ Value = stripslashes ($ value );
}
// The mysql_real_escape_string function exists and uses it to process strings.
If (function_exists ("mysql_real_escape_string ")){
$ Value = mysql_real_escape_string ($ value );
} // When PHP <4.3.0 uses the addslashes () function to filter
Else {
$ Value = addslashes ($ value );
}
Return $ value;
}

We use the SQL _quote () function compiled above to filter input strings:
 
$ Username = $ _ POST [username];
Query = "SELECT * FROM users WHERE username =". SQL _quote ($ username )."";
 
When the entire function is not used, we can use "OR 1 = 1" to bypass user verification. The SQL statement becomes:
 
Query = "SELECT * FROM users WHERE username = OR 1 = 1 ";
 
After SQL _quote () function is used, the SQL statement becomes:
 
Query = "SELECT * FROM users WHERE username = OR 1 = 1 ";
 
Therefore, this statement becomes more secure. Attackers can bypass verification from this statement alone.
 
Summary
This article mainly discusses the prevention of SQL injection attacks by PHP, referring to PHP Security: Basic PHP Security and other articles, which have been translated and compiled. If you are interested, you can refer to the original article PHP Security: Basic PHP Security at http://www.phpit.net/article/php-security-basic /.

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.