Php Security filter _ PHP Tutorial

Source: Internet
Author: User
Php Security filtering. Php Security Filter * ansic code-Url code table: www.w3school.com.cntagshtml_ref_urlencode.html authorization php Security filter

/* Ansic code-Url code: http://www.w3school.com.cn/tags/html_ref_urlencode.html

Bytes -----------------------------------------------------------------------------------------------------------------

1. verify and filter user input

Even the most common alphanumeric input can be dangerous, listing several characters that may cause security problems:

! $ ^ &*()~ [] \ | {} '"; <>? -'

There may be special characters in the database:

'";\

There are also some non-printable characters:

Character \ x00 or ASCII 0, NULL or FALSE

Characters \ x10 and \ x13, or ASCII 10 and 13, \ n \ r

Character \ x1a or ASCII 26, indicating the end of the file

Incorrect parameter type may also lead to unexpected errors in the program.

Too many parameter values may cause overflow and other errors.

2. filter file paths and names

The file name cannot contain binary data, otherwise it may cause problems.

Some systems allow Unicode multi-byte encoding file names, but do not use ASCII characters.

Although Unix systems can use almost any symbol in file name settings, use-and _ as much as possible to avoid other characters.

Specify the length of the file name.

3. prevent SQL injection

Check the type of user input. you can use the following method when the user inputs a number:

Use the is_int () function (or is_integer () or is_long () function)

Use the gettype () function

Use the intval () function

Use the settype () function

Check the length of the user input string using the strlen () function.

Use the strtotime () function to check whether the date or time is valid.

4. prevent XSS attacks

A common method for xss attacks is to inject HTML elements to execute js scripts. php has built-in defense functions (such as htmlentities or htmlspecialchars)

5. filter URLs submitted by users

If you allow a user to enter a URL to call an image or link, you must ensure that it does not pass in javascript: or vbscript: or data: or other non-http protocols.

You can use the php built-in function parse_url () to split the URL and then make a judgment.

6. prevent remote execution-the following table lists Shell-related characters:

Remote execution usually uses php code to execute functions such as eval (), or calls command execution such as exec (), passthru (), proc_open (), shell_exec (), system () or popen ().

Php code injection: php provides developers with a lot of methods to call and allow php scripts. we need to filter user-controllable data.

7. Shell command execution

PHP provides some functions that can directly execute system commands, such as the exec () function or '(reverse quotation marks ).

The PHP Security mode provides some protection, but there are also some ways to bypass the security mode:

1. Upload a Perl script, or a Python or Ruby environment supported by the server to execute scripts in other languages to bypass the PHP Security mode.

2. bypass the security mode by exploiting the system buffer overflow vulnerability.

Shell-related characters:

Name character ASCII hexadecimal URL encoding HTML

Line Feed 10 \ x0a % 0a

Exclamation point! 33 \ x21 % 21!

Double quotation marks "34 \ x22 % 22" or"

Dollar sign $36 \ x24 % 24 $

Connector & 38 \ x26 % 26 & or & # amp

Single quotes '39 \ x27 % 27'

Left Parenthesis (40 \ x28 % 28 (

Parentheses) 41 \ x29 % 29)

Asterisk * 42 \ x2a % 2a *

Hyphen-45 \ x2d % 2d-

Semicolon; 59 \ x3b % 3b;

Left angle brackets <60 \ x3c % 3c <

Angle brackets> 62 \ x3e % 3e>

Question mark? 63 \ x3f % 3f?

Square brackets [91 \ x5b % 5b [

Backslash \ 92 \ x5c % 5c \

Square brackets] 93 \ x5d % 5d]

Insert character ^ 94 \ x5e % 5e ^

Backticks '96 \ x60 % 60'

Left curly braces {123 \ x7b % 7b {

Pipeline operator | 124 \ x7c % 7c |

Right curly braces} 125 \ x7d % 7d}

Tilde ~ 126 \ x7e % 7e ~

Bytes -----------------------------------------------------------------------------------------------------------------

Security filter function code */

/**

* Security filter input [jb]

*/

Function check_str ($ string, $ isurl = false)

{

$ String = preg_replace ('/[\ x00-\ x08 \ x0B \ x0C \ x0E-\ x1F]/', '', $ string ); // remove control characters

$ String = str_replace (array ("\ 0", "% 00", "\ r"), '', $ string); // \ 0 represents the ASCII 0x00 character, it is usually used as the string end sign; these three are potentially harmful characters

Empty ($ isurl) & $ string = preg_replace ("/&(?! (# [0-9] + | [a-z] +);)/si ", '&', $ string); // you can use & # xxx in HTML; to encode some characters, such as spaces ),? Unicode characters, (?! B) indicates that A is not followed by B, so the author wants to keep it? Similar HTML encoding characters, remove other problematic characters

$ String = str_replace (array ("% 3C", '<'), '<', $ string); // Convert the ascii '<' to '<';

$ String = str_replace (array ("% 3E", '>'), '>', $ string );

$ String = str_replace (array ('"'," '"," \ t ",''), array (', '', ''), $ string );

Returntrim ($ string );

}

/**

* Security filtering-filtering of insecure parameters, such as javascript, css, iframes, and object, with a high level of filtering

* @ Param string $ value the value to be filtered

* @ Return string

*/

Function fliter_script ($ value ){

$ Value = preg_replace ("/(javascript :)? On (click | load | key | mouse | error | abort | move | unload | change | dblclick | move | reset | resize | submit)/I ", "& 111n \ 2", $ value );

$ Value = preg_replace ("/(.*?) <\/Script>/si "," ", $ value );

$ Value = preg_replace ("/(.*?) <\/Iframe>/si "," ", $ value );

$ Value = preg_replace ("// iesU", '', $ value );

Return $ value;

}

/**

* Security filtering-HTML tag filtering

* @ Param string $ value the value to be filtered

* @ Return string

*/

Function fliter_html ($ value ){

If (function_exists ('htmlspecialchars') return htmlspecialchars ($ value );

Returnstr_replace (array ("&", '"'," '"," <","> "), array ("&","\"","'", "<", ">"), $ value );

}

/**

* Security filtering-underline incoming data to prevent SQL injection

* @ Param string $ value the value to be filtered

* @ Return string

*/

Function fliter_ SQL ($ value ){

$ SQL = array ("select", 'insert', "update", "delete ","\'","\/\*","\. \. \/","\. \/"," union "," into "," load_file "," outfile ");

$ SQL _re = array ("","","","","","","","","","","", "");

Returnstr_replace ($ SQL, $ SQL _re, $ value );

}

/**

* Security filtering-General data filtering

* @ Param string $ value the variable to be filtered

* @ Return string | array

*/

Function fliter_escape ($ value ){

If (is_array ($ value )){

Foreach ($ value as $ k => $ v ){

$ Value [$ k] = self: fliter_str ($ v );

}

} Else {

$ Value = self: fliter_str ($ value );

}

Return $ value;

}

/**

* Security filtering-string filtering filters out special harmful characters

* @ Param string $ value the value to be filtered

* @ Return string

*/

Function fliter_str ($ value ){

$ Badstr = array ("\ 0", "% 00", "\ r", '&', '', '"', "'", "<", ">", "", "% 3C", "% 3E ");

$ Newstr = array ('', '&','', '"', '''," <","> ","", "<", "> ");

$ Value = str_replace ($ badstr, $ newstr, $ value );

$ Value = preg_replace ('/& (# (\ d {3, 5} | x [a-fA-F0-9] {4});)/', '& \ 1 ', $ value );

Return $ value;

}

/**

* Secure conversion of private traffic

* @ Param string $ fileName

* @ Return string

*/

Function filter_dir ($ fileName ){

$ Tmpname = strtolower ($ fileName );

$ Temp = array (':/', "\ 0 ","..");

If (str_replace ($ temp, '', $ tmpname )! ==$ Tmpname ){

Returnfalse;

}

Return $ fileName;

}

/**

* Filter directories

* @ Param string $ path

* @ Return array

*/

Public function filter_path ($ path ){

$ Path = str_replace (array ("'",' # ',' = ', ''',' $ ',' % ','&',';'), '', $ path );

Returnrtrim (preg_replace ('/(\/) {2 ,}| (\) {1 ,}/', '/', $ path ),'/');

}

/**

* Filter PHP labels

* @ Param string $ string

* @ Return string

*/

Public function filter_phptag ($ string ){

Returnstr_replace (array (''), array (' '), $ String );

}

/**

* Security filtering-return functions

* @ Param string $ value the value to be filtered

* @ Return string

*/

Public function str_out ($ value ){

$ Badstr = array ("<", ">", "% 3C", "% 3E ");

$ Newstr = array ("<", ">", "<", "> ");

$ Value = str_replace ($ newstr, $ badstr, $ value );

Returnstripslashes ($ value); // underline

}

Http://www.bkjia.com/PHPjc/1055558.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1055558.htmlTechArticlephp security filter/* ansic code-Url code table: http://www.w3school.com.cn/tags/html_ref_urlencode.html small -----------------------------------------------------------------------------------...

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.