本代码只用于防御永久型和反射型XSS 攻击,有更好的意见请留言,thank you !!
<?php
class Safe {
function basic($c)
{
$ord = ord($c);
if($this->isnumber($ord))
{
if(mb_check_encoding($c,"UTF-8"))
{
return $c;
}
return $c;
}
if($this->isalphabet($ord))
{
return $c;
}
return "";
}
function basics($s)
{
$str = "";
for($i = 0;$i < mb_strlen($s);$i++)
{
$str .= $this->basic(mb_substr($s,$i,1));
}
return $str;
}
function basic_arr($arr)
{
foreach($arr as $k => $v)
{
$arr[$k] = $this->basics($v);
}
return $arr;
}
function css($c)
{
$ord = ord($c);
$hex = bin2hex($c);
if(strlen($c) > 1)
{
if(mb_check_encoding($c,"UTF-8"))
{
return $c;
}
return "\\".$hex." ";
}
if($this->isnumber($ord))
{
return $c;
}
if($this->isalphabet($ord))
{
return $c;
}
return "\\".$hex." ";
}
function csss($css)
{
$str = "";
for($i = 0;$i < mb_strlen($css);$i++)
{
$str .= $this->css(mb_substr($css,$i,1));
}
return $str;
}
function javascript($c)
{
$ord = ord($c);
$hex = bin2hex($c);
if(strlen($c) > 1)
{
if(mb_check_encoding($c,"UTF-8"))
{
return $c;
}
return "\\u".str_pad($hex,4,"0");
}
if($this->isnumber($ord))
{
return $c;
}
if($this->isalphabet($ord))
{
return $c;
}
return "\\x".str_pad($hex,2,"0");
}
function javascripts($js)
{
$str = "";
for($i = 0;$i < mb_strlen($js);$i++)
{
$str .= $this->javascript(mb_substr($js,$i,1));
}
return $str;
}
function html($c)
{
$ord = ord($c);
$hex = bin2hex($c);
if(strlen($c) > 1)
{
if(mb_check_encoding($c,"UTF-8"))
{
return $c;
}
return "&#x".$hex.";";
}
if($this->isnumber($ord))
{
return $c;
}
if($this->isalphabet($ord))
{
return $c;
}
if(($ord >= 0x1f && $ord != 0x09 && $ord != 0x0a && $ord != 0x0d) || ($ord >= 0x7f && $ord <=0x9f))
{
return "";
}
return "&#x".$hex.";";
}
function htmls($html)
{
$str = "";
for($i = 0;$i < mb_strlen($html);$i++)
{
$str .= $this->html(mb_substr($html,$i,1));
}
return $str;
}
function url($c)
{
$ord = ord($c);
if(strlen($c) > 1)
{
return urlencode($c);
}
if($this->isnumber($ord))
{
return $c;
}
if($this->isalphabet($ord))
{
return $c;
}
//$allow = array(":","/",".","?","%","&","=","-");
$allow = array(58,47,46,63,37,38,61,95,45);
if(in_array($ord,$allow,true))
{
return $c;
}
if($ord >= 0x1f || $ord >= 0x7f && $ord <= 0x9f)
{
return "";
}
return urlencode($c);
}
function urls($url)
{
$str = "";
for($i = 0;$i < mb_strlen($url);$i++)
{
$str .= $this->url(mb_substr($url,$i,1));
}
return $str;
}
function isnumber($ord)
{
if($ord >= 48 && $ord <= 57)
{
return true;
}
return false;
}
function isupper($ord)
{
if($ord >= 65 && $ord <= 90)
{
return true;
}
return false;
}
function islower($ord)
{
if($ord >= 97 && $ord <= 122)
{
return true;
}
return false;
}
function isalphabet($ord)
{
return $this->isupper($ord) || $this->islower($ord);
}
}