PHP XSS Attack Prevention Code

Source: Internet
Author: User
Tags html tags ord printable characters strlen

Example

The easiest way to use PHP's own Htmlspecialchars function is to convert character content into HTML entities

The code is as follows Copy Code

<?php
if (isset ($_post[' name ')) {
$str = Trim ($_post[' name ')); Clean space
$str = Strip_tags ($STR); Filter HTML Tags
$str = Htmlspecialchars ($STR); Convert character content to HTML entity
$str = Addslashes ($STR);
Echo $str;
}
?>
<form method= "POST" action= "" >
<input name= "name" type= "Text" >
<input type= "Submit" value= "submitted" >
</form>

Example

The encapsulation of the Htmlspecialchars function also replaces some characters that are known to be dangerous

The code is as follows Copy Code

/**
* Encapsulation of the Htmlspecialchars function
* @param $item
* @param string $encoding
* @return array|mixed|string
*/
function Clear_xss ($item, $encoding = ' UTF-8 ') {
if (Is_array ($item)) {
Return Array_map (' Clear_xss ', $item);
} else {
$item = Htmlspecialchars ($item, Ent_quotes, $encoding);

Www.111cn.net, the following is from CI.
$no = '/%0[0-8bcef]/';
$item = Preg_replace ($no, ', $item);
$no = '/%1[0-9a-f]/';
$item = Preg_replace ($no, ', $item);
$no = '/[--]+/s ';
$item = Preg_replace ($no, ', $item);
return $item;
}
}


This provides a function to filter illegal scripts:

The code is as follows Copy Code

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 <ja vascript> 
  //Note this have to handle splits with,, and later since, they *are* allowed in Some inputs 
   $val = preg_replace ('/([-][-][-])/', ', $val);  

  //Straight replacements, the user should never need these since they ' re normal characters 
&nbs p; //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 are Optional and go up to 8 chars 

& #x0040 @ search for the hex values
$val = Preg_replace ('/(&#[x| x]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 {0,8} '. Ord ($search [$i]). /', $search [$i], $val); with A;
}

Now the only www.111Cn.net remaining whitespace attacks are, 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 ', ' onrowenter ', ' 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. = ' (&#[x| x]0{0,8} ([9][a][b]);
$pattern. = ' | (& #0 {0,8} ([9][10][13]);
$pattern. = ')? ';
}
$pattern. = $ra [$i] [$j];
}
$pattern. = '/I ';
$replacement = substr ($ra [$i], 0, 2). ' <x> '. 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;
}
}
}
}

The last side of this function is mainly used by some foreign experts wrote, to know the dangerous function of more knowledge, so we put it all in and then replace the operation.

There's a little cloud-dwelling community to remind you that some friends use htmlentities () to filter, the function default code for ISO-8859-1, if your illegal script code for other, then may not filter out, while the browser can be identified and implemented Oh, so have to find a way to solve it.

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.