PHP防注入安全代码
PHP
#
防注入2012-12-21 15:43
怕网站被注入的朋友们看过来了,今天分享个代码。
1.将safe.func.php传到要包含的文件的目录
2.在页面中加入防护,有两种做法,根据情况二选一即可:
a).在所需要防护的页面加入代码
require_once('safe.func.php');
就可以做到页面防注入、跨站
如果想整站防注,就在网站的一个公用文件中,如数据库链接文件config.inc.php中!
添加require_once('safe.func.php');来调用本代码
常用php系统添加文件
PHPCMS V9 phpcmsase.php
PHPWIND8.7 datasql_config.php
DEDECMS5.7 datacommon.inc.php
DiscuzX2 configconfig_global.php
Wordpress wp-config.php
Metinfo includehead.php
b).在每个文件最前加上代码
在php.ini中找到:
Automatically add files before or after any PHP document.
auto_prepend_file = safe.func.php路径;
safe.func.php 代码如下:
08 | function safe_custom_error( $errno , $errstr , $errfile , $errline ) { |
09 | echo "<b>Error number:</b> [$errno],error on line $errline in $errfile<br />" ; |
14 | set_error_handler( "safe_custom_error" , E_ERROR); |
16 | function safe_stop_attack( $k , $v , $method =0) { |
18 | "'|(and|or).+?(>|<|=|in|like)|/*.+?*/|<s*script|EXEC|UNION.+?SELECT|UPDATE.+?SET|INSERTs+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)s+(TABLE|DATABASE)" , |
19 | "(and|or).{1,6}?(=|>|<|in|like)|/*.+?*/|<s*script|EXEC|UNION.+?SELECT|UPDATE.+?SET|INSERTs+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)s+(TABLE|DATABASE)" |
22 | $filter = isset( $filter [ $method ]) ? $filter [ $method ] : $filter [0]; |
27 | if (preg_match( "/" . $filter . "/is" , $v ) == 1) { |
28 | exit ( "本次操作已记录。请不要继续非法操作。" ); |
33 | foreach ( $_GET as $k => $v ) safe_stop_attack( $k , $v , 0); |
36 | foreach ( $_POST as $k => $v ) safe_stop_attack( $k , $v , 1); |
39 | foreach ( $_COOKIE as $k => $v ) safe_stop_attack( $k , $v , 1); |
相关文章