PHP using Str_replace anti-injection Method _php Tutorial

Source: Internet
Author: User
Tags printable characters
PHP various filter character functions
Copy CodeThe code is as follows:
/**
* Safe Filter function
*
* @param $string
* @return String
*/
function Safe_replace ($string) {
$string = Str_replace ('%20 ', ', $string);
$string = Str_replace ('%27 ', ' ', $string);
$string = Str_replace ('%2527 ', ' ', $string);
$string = Str_replace (' * ', ' ', $string);
$string = Str_replace (' "', '" ', $string);
$string = Str_replace ("'", "', $string);
$string = Str_replace (' "', ' ', $string);
$string = Str_replace ('; ', ' ', $string);
$string = Str_replace (' < ', ' < ', $string);
$string = Str_replace (' > ', ' > ', $string);
$string = Str_replace ("{", "', $string);
$string = Str_replace ('} ', ' ', $string);
$string = Str_replace (', ', ', $string);
return $string;
}
?>


/**
* Returns a string or array that has been processed by addslashes
* @param $string string or array to be processed
* @return Mixed
*/
function New_addslashes ($string) {
if (!is_array ($string)) return addslashes ($string);
foreach ($string as $key = + $val) $string [$key] = new_addslashes ($val);
return $string;
}
?>


Secure processing of the requested string
/*
$safestep
0 for non-processing,
1 to prohibit unsafe HTML content (JavaScript, etc.),
2 completely disables HTML content and replaces some unsafe strings (such as: eval (, Union, CONCAT (、--、, etc.)
*/
function Stringsafe ($str, $safestep =-1) {
$safestep = ($safestep >-1)? $safestep: 1;
if ($safestep = = 1) {
$str = Preg_replace ("#script: #i", "Script:", $STR);
$str = Preg_replace ("#<[/]{0,1} (LINK|META|IFR|FRA|SCR) [^>]*> #isU", ", $str);
$str = Preg_replace ("#[]{1,}#", ", $str);
return $str;
}else if ($safestep = = 2) {
$str = Addslashes (Htmlspecialchars (Stripslashes ($STR)));
$str = Preg_replace ("#eval #i", ' eval ', $str);
$str = Preg_replace ("#union #i", ' Union ', $STR);
$str = Preg_replace ("#concat #i", ' concat ', $str);
$str = Preg_replace ("#--#", '--', $str);
$str = Preg_replace ("#[]{1,}#", ", $str);
return $str;
}else{
return $str;
}
}
?>


/**
+----------------------------------------------------------
* Output secure HTML for filtering hazard codes
+----------------------------------------------------------
* @access Public
+----------------------------------------------------------
* @param string $text to be processed
* @param mixed $tags allowed list of tags, such as table|td|th|td
+----------------------------------------------------------
* @return String
+----------------------------------------------------------
*/
static public Function safehtml ($text, $tags = null)
{
$text = Trim ($text);
Fully filtered annotations
$text = Preg_replace ('/ /', ', $text);
Fully filter Dynamic code
$text = Preg_replace ('/ /', ', $text);
Full Filter JS
$text = Preg_replace ('/ /', ', $text);
$text = Str_replace (' [', ' [', $text);
$text = Str_replace ('] ', '] ', $text);
$text = Str_replace (' | ', ' | ', $text);
Filter line breaks
$text = Preg_replace ('/?/', ' ', $text);
Br
$text = Preg_replace ('/ /I ', ' [BR] ', $text);
$text = Preg_replace ('/([br]s*) {10,}/i ', ' [BR] ', $text);
Filter for dangerous properties, such as: Filter on event Lang JS
while (Preg_match ('/(<[^><]+) (LANG|ON|ACTION|BACKGROUND|CODEBASE|DYNSRC|LOWSRC) [^><]+/i ', $text, $ MAT)) {
$text =str_replace ($mat [0], $mat [1], $text);
}
while (Preg_match ('/(<[^><]+) (window.| javascript:|js:|about:|file:|document.| Vbs:|cookie) ([^><]*)/I ', $text, $mat)) {
$text =str_replace ($mat [0], $mat [1]. $mat [3], $text);
}
if (empty ($allowTags)) {$allowTags = self:: $htmlTags [' Allow '];}
Allowed HTML tags
$text = Preg_replace ('/< ('. $allowTags. ') ([^><[]]*) >/i ', ' [n] ', $text);
Filtering Extra HTML
if (empty ($banTag)) {$banTag = self:: $htmlTags [' ban '];}
$text = Preg_replace ('/ <]*>/i ', ', $text);
Filter legitimate HTML tags
while (Preg_match ('/< ([a-z]+) [^><[]]*>[^><]* /I ', $text, $mat)) {
$text =str_replace ($mat [0],str_replace (' > ', '] ', Str_replace (' < ', ' [', $mat [0])), $text);
}
Convert quotation marks
while (Preg_match ('/([[^[]]*=s*) (' | ') ([^2=[]]+) 2 ([^[]]*])/I ', $text, $mat)) {
$text =str_replace ($mat [0], $mat [1]. ' | '. $mat [3]. ' | '. $mat [4], $text);
}
Null attribute Conversions
$text = Str_replace ("', ' | | ', $text);
$text = Str_replace (' "" ', ' | | ', $text);
Filter the wrong single quotation marks
while (Preg_match ('/[[^[]]* (' | ') [^[]]*]/i ', $text, $mat)) {
$text =str_replace ($mat [0],str_replace ($mat [1], ", $mat [0]), $text);
}
Convert all other illegal < >
$text = Str_replace (' < ', ' < ', $text);
$text = Str_replace (' > ', ' > ', $text);
$text = Str_replace (' "', '" ', $text);
Inverse conversion
$text = Str_replace (' [', ' < ', $text);
$text = Str_replace ('] ', ' > ', $text);
$text = Str_replace (' | ', ' "', $text);
Filter extra spaces
$text = Str_replace (', ', ', $text);
return $text;
}
?>


function Removexss ($val) {
Remove all non-printable characters. CR (0a) and LF (0b) and TAB (9) are allowed
This prevents some character re-spacing such as
Note that you had to handle splits with,, and later since they *are* allowed in some//inputs
$val = Preg_replace ('/([x00-x08,x0b-x0c,x0e-x19])/', ' ', $val);
Straight replacements, the user should never need these since they ' re normal characters
This prevents like
$search = ' abcdefghijklmnopqrstuvwxyz ';
$search. = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ';
$search. = ' 1234567890!@#$%^&* () ';
$search. = ' ~ ' ";:? +/={}[]-_| ';
for ($i = 0; $i < strlen ($search); $i + +) {
// ;? Matches the; which is optional
0{0,7} matches any padded zeros, which is optional and go up to 8 chars
@ search for the hex values
$val = Preg_replace ('/(&#[xx]0{0,8} '. Dechex (Ord ($search [$i])). /I ', $search [$i], $val);//with A;
@ @ 0{0,7} matches ' 0 ' zero to seven times
$val = Preg_replace ('/({0,8} '. Ord ($search [$i]). ';? ' /', $search [$i], $val); with A;
}
Now the only remaining whitespace attacks is, and
$ra 1 = Array (' javascript ', ' VBScript ', ' expression ', ' applets ', ' meta ', ' xml ', ' blink ', ' link ', ' style ', ' script ', ' embed ', ' Object ', ' iframe ', ' frame ', ' frameset ', ' ilayer ', ' layer ', ' bgsound ', ' title ', ' base ';
$ra 2 = Array (' onabort ', ' onactivate ', ' onafterprint ', ' onafterupdate ', ' onbeforeactivate ', ' onbeforecopy ', ' Onbeforecut ', ' onbeforedeactivate ', ' onbeforeeditfocus ', ' onbeforepaste ', ' onbeforeprint ', ' onbeforeunload ', ' Onbeforeupdate ', ' onblur ', ' onbounce ', ' oncellchange ', ' onchange ', ' onclick ', ' oncontextmenu ', ' oncontrolselect ', ' Oncopy ', ' oncut ', ' ondataavailable ', ' ondatasetchanged ', ' ondatasetcomplete ', ' ondblclick ', ' ondeactivate ', ' Ondrag ', ' Ondragend ', ' ondragenter ', ' ondragleave ', ' ondragover ', ' ondragstart ', ' ondrop ', ' onerror ', ' onerrorupdate ', ' Onfilterchange ', ' onfinish ', ' onfocus ', ' onfocusin ', ' onfocusout ', ' onhelp ', ' onkeydown ', ' onkeypress ', ' onkeyup ', ' Onlayoutcomplete ', ' onload ', ' onlosecapture ', ' onmousedown ', ' onmouseenter ', ' onmouseleave ', ' onmousemove ', ' onMouseOut ', ' onmouseover ', ' onmouseup ', ' onmousewheel ', ' onmove ', ' onmoveend ', ' onmovestart ', ' onpaste ', ' Onpropertychange ', ' onreadystatechange ', ' onreset ', ' onresize ', ' onresizeend ', ' onresizestart ', ' onrowent 'Er ', ' onrowexit ', ' onrowsdelete ', ' onrowsinserted ', ' onscroll ', ' onselect ', ' onselectionchange ', ' onselectstart ', ' OnStart ', ' onstop ', ' onsubmit ', ' onunload ');
$ra = Array_merge ($ra 1, $ra 2);
$found = true; Keep replacing as long as the previous round replaced something
while ($found = = True) {
$val _before = $val;
for ($i = 0; $i < sizeof ($RA); $i + +) {
$pattern = '/';
for ($j = 0; $j < strlen ($ra [$i]); $j + +) {
if ($j > 0) {
$pattern. = ' (';
$pattern. = ' (&#[xx]0{0,8} ([9ab]);) ';
$pattern. = ' | ';
$pattern. = ' | ({0,8} ([9|10|13]);) ';
$pattern. = ') * ';
}
$pattern. = $ra [$i] [$j];
}
$pattern. = '/I ';
$replacement = substr ($ra [$i], 0, 2). ' '. substr ($ra [$i], 2);//Add in <> to nerf the tag
$val = Preg_replace ($pattern, $replacement, $val); Filter out the hex tags
if ($val _before = = $val) {
No replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}
?>

http://www.bkjia.com/PHPjc/825062.html www.bkjia.com true http://www.bkjia.com/PHPjc/825062.html techarticle PHP various filter character functions copy code as follows:? PHP/** * Security Filter function * * @param $string * @return String */function Safe_replace ($string) {$stri ng = Str_replace (' ...

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