This article will summarize some common methods for preventing php injection and SQL Injection in php, htmlspecialchars/addslashes/stripslashes/strip_tags/mysql_real_escape_string and other functions are provided in php. For more information, see.
The following is a summary of Special Character Processing in common forms:
Test string:
The Code is as follows: |
Copy code |
$ Dbstr = 'd: test <A href = "http://www.bKjia. c0m"> http://www.bKjia. c0m </a>, Tian Yuan blog '! = '1' OR '1' </DIV> <Script language = "javascript" type = "text/javascript"> alert ("Fail"); </script> <? Php echo "<br/> php output";?> ';
|
Test code:
The Code is as follows: |
Copy code |
Header ("Content-Type: text/html; charset = UTF-8 "); Echo "------------------------------------------------------ <br/> rn "; Echo $ dbstr. "<br/> rn ------------------------------------------------------ <br/> rn "; $ Str = fnAddSlashes ($ _ POST ['dd']); Echo $ str. "<br/> rn ------------------------------------------------------ <br/> rn "; $ Str = preg_replace ("/s (? = S)/"," \ 1 ", $ str); // multiple consecutive spaces are retained for only one $ Str = str_replace ("r", "<br/>", $ str ); $ Str = str_replace ("n", "<br/>", $ str ); $ Str = preg_replace ("/(<br/?>) +)/I "," <br/> ", $ str); // multiple consecutive tags <br/> retain only one $ Str = stripslashes ($ str ); Echo strip_tags ($ str). "<br/> rn ------------------------------------------------------ <br/> rn "; Echo htmlspecialchars ($ str). "<br/> rn ------------------------------------------------------ <br/> rn "; Echo htmlentities ($ str). "<br/> rn ------------------------------------------------------ <br/> rn "; Echo mysql_escape_string ($ str). "<br/> rn ------------------------------------------------------ <br/> rn "; |
String contains: backslash path, single double quotation marks, HTML tags, links, unblocked HTML tags, database syntax error tolerance, JS execution judgment, PHP Execution judgment, multiple consecutive carriage return line breaks and spaces. Some of these concepts are inclusive.
Ii. Data Processing for form submission
1. Force Add a backslash
Because some hosts enable the magic reference get_magic_quotes_gpc by default, and some may disable it, it is best to add a backslash to the program. This can be processed in a unified manner. The characters include single quotes, double quotation marks, and backslash.
The Code is as follows: |
Copy code |
Function fnAddSlashes ($ data) { If (! Get_magic_quotes_gpc () // only escapes POST/GET/cookie data. Return is_array ($ data )? Array_map ('addslashes ', $ data): addslashes ($ data ); Else Return $ data; } |
2. Special Character Processing
The following are several common string processing methods, which can be selected based on actual conditions. Because the data in the submitted form has been escaped once, if you need to replace or filter the content, consider the effect of addslashes on the relevant characters. When replacing or searching, consider adding a backslash. Replacement of other characters is not affected, for example, replacement of rn.
A. retain only one consecutive Space
The Code is as follows: |
Copy code |
$ Data = preg_replace ("/s (? = S)/"," \ 1 ", $ data); // multiple consecutive spaces are retained for only one |
B. Replace line breaks with <br/>
The Code is as follows: |
Copy code |
$ Data = str_replace ("r", "<br/>", $ data ); $ Data = str_replace ("n", "<br/>", $ data ); |
// In html, the default value is <br> not blocked. In xhtml, <br/> blocked. We recommend that you use <br/>. More differences:
C. Multiple consecutive records <br/> retain only one
The Code is as follows: |
Copy code |
$ Data = preg_replace ("/(<br/?>) +)/I "," <br/> ", $ data); // multiple consecutive <br/> labels retain only one
|
D. filter all HTML tags
This method filters all potentially dangerous tags, including HTML, Link, unblocked HTML tags, JS, and PHP.
Use the strip_tags ($ data) Function)
After this function is used, all HTML tags (including links), PHP tags, and JS Code are filtered out. The link retains the original link only removes the <a> tag and href content, PHP and JS tags are removed as a whole, including the intermediate content, such:
E. Do not filter tags, just HTML them
This method processes all the original submitted content in plain text.
Using the htmlspecialchars ($ data) function, after the function is executed, all submitted data is displayed in plain text, for example:
Execution result using the htmlentities function (garbled characters are displayed in Chinese ):
3. Write data to the database
Because advanced trusted users can directly write data to the database after using addslashes ($ data), but addslashes cannot intercept single quotes replaced by 0xbf27, it is best to use mysql_real_escape_string or mysql_escape_string for escape, however, you need to remove the backslash before escaping (assuming that addslashes is enabled by default ).
The Code is as follows: |
Copy code |
Function fnEscapeStr ($ data) { If (get_magic_quotes_gpc ()) { $ Data = stripslashes ($ value ); } $ Data = "'". mysql_escape_string ($ value )."'"; Return $ data; } $ Data = fnEscapeStr ($ data ); |
PHP general anti-injection Security Code
The Code is as follows: |
Copy code |
Note: Determines whether the passed variable contains invalid characters. Such as $ _ POST and $ _ GET Function: Anti-Injection **************************/ // Invalid characters to be filtered $ ArrFiltrate = array ("'", ";", "union "); // The url to be redirected after an error occurs. If this parameter is left blank, the previous page is displayed by default. $ StrGoUrl = ""; // Whether the value in the array exists Function FunStringExist ($ StrFiltrate, $ ArrFiltrate ){ Foreach ($ ArrFiltrate as $ key => $ value ){ If (eregi ($ value, $ StrFiltrate )){ Return true; } } Return false; } // Merge $ _ POST and $ _ GET If (function_exists (array_merge )){ $ ArrPostAndGet = array_merge ($ HTTP_POST_VARS, $ HTTP_GET_VARS ); } Else { Foreach ($ HTTP_POST_VARS as $ key => $ value ){ $ ArrPostAndGet [] = $ value; } Foreach ($ HTTP_GET_VARS as $ key => $ value ){ $ ArrPostAndGet [] = $ value; } } // Verification starts Foreach ($ ArrPostAndGet as $ key => $ value ){ If (FunStringExist ($ value, $ ArrFiltrate )){ Echo "alert (/" Neeao prompt, illegal character /");"; If (empty ($ StrGoUrl )){ Echo "history. go (-1 );"; } Else { Echo "window. location =/" ". $ StrGoUrl ."/";"; } Exit; } } ?>
|
/*************************
Save as checkpostandget. php
Add include ("checkpostandget. php") before each php file.