php安全防护代码

Posted woxiaohaha

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php安全防护代码相关的知识,希望对你有一定的参考价值。

<?php
//判断是否开启防护规则
$localtime=date(‘y-m-d H:i:s:ms‘,time());

echo $localtime . ‘<br>‘;
//error_reporting(E_ERROR); 
$isopen = 1;
if(isset($_GET[‘op_sec_rule_open‘]))
	$isopen =intval($_GET[‘op_sec_rule_open‘]); 

//当参数值在20~2048 之间时,进行检查
function StopAttack($StrFiltKey,$StrFiltValue,$ArrFiltReq,$data=‘get‘){  

	if(is_array($StrFiltValue))
	{
		$StrFiltValue=implode($StrFiltValue);
	}  
	$length = strlen($StrFiltValue);
	if($length > 20 && $length < 2048)
	{
		
		if (preg_match("/".$ArrFiltReq."/is",$StrFiltValue)==1){   
		  
		  $sec_method = $_SERVER[‘REQUEST_METHOD‘];
		  $sec_referer = ‘‘;
		  if(isset($_SERVER[‘HTTP_REFERER‘]))
			  $sec_referer = $_SERVER[‘HTTP_REFERER‘];
		  $sec_uri = $_SERVER["REQUEST_URI"];
		  $sec_host = $_SERVER["HTTP_HOST"];
		  $sec_payload = ‘‘;
		  if($data == ‘post‘)
		  {
			  foreach($_POST as $key=>$value){ 
				if(empty($sec_payload))
				{
					$sec_payload = $key.‘=‘.$value;
				}else
				{
					$sec_payload =$payload.‘&‘.$key.‘=‘.$value;
				}			
			  }
		  }else if($data == ‘cookie‘)
		  {
			   foreach($_COOKIE as $key=>$value){ 
					if(empty($sec_payload))
					{
						$sec_payload = $key.‘=‘.$value;
					}else
					{
						$sec_payload =$sec_payload.‘;‘.$key.‘=‘.$value;
					}			
			  }
		  }
		  $arr = array (‘method‘=>$sec_method,‘referer‘=>$sec_referer,‘host‘=>$sec_host,‘url‘=>$sec_uri,‘payload‘=>$sec_payload,‘datatype‘ => $data);
		  $sec_data =  json_encode($arr);
		  // 匹配成功后,只记录暂时不终止
		  $sec_server = ‘http://website80/alert_v1.php?param=‘.$sec_data;
		  //file_get_contents($sec_server);
		  print "vdian security notice:Illegal operation!";
		  //exit();
	    } 
	}
	
}
if($isopen == 1)
{
	$getfilter="<i?frame\\b|<\\s*script\\b|<.+?>|UNION.+?SELECT|SELECT.+?FROM";
	$postfilter="<\\s*script\\b|UNION.+?SELECT|SELECT.+?FROM";
	$cookiefilter="UNION.+?SELECT|SELECT.+?FROM";

	foreach($_GET as $key=>$value){ 
		StopAttack($key,$value,$getfilter);
	}
	foreach($_POST as $key=>$value){ 
		StopAttack($key,$value,$postfilter,$data=‘post‘);
	}
	foreach($_COOKIE as $key=>$value){ 
		StopAttack($key,$value,$cookiefilter,$data=‘cookie‘);
	}
	unset($getfilter);
	unset($postfilter);
	unset($cookiefilter);
}
unset($isopen);
$localtime=date(‘y-m-d H:i:s:ms‘,time());

echo $localtime . ‘<br>‘;
?>

 

以上是关于php安全防护代码的主要内容,如果未能解决你的问题,请参考以下文章

PHP代码-psysh调试代码片段工具

比较有用的php代码片段

超实用的php代码片段

php Yoast SEO规范输出的代码片段

php Yoast SEO规范输出的代码片段

使用 NodeJS 和 JSDOM/jQuery 从代码片段构建 PHP 页面