首页 > php教程 > PHP源码 > 正文

安全 防XSS跨站 SQL注入

PHP中文网
发布: 2016-05-25 17:08:22
原创
1250人浏览过

sql注入

<?php
 
defined('TC_CMS') or exit('Access Denied');
 
/**
 * TC_CMS
 * =======================================================
 * 版权所有 (C) 2010-2020 www.teamcen.com,并保留所有权利。
 * 网站地址: http://www.teamcen.com
 * Q Q: 9877633
 * -------------------------------------------------------
 *
 * @author :     milkcy <milkcy@foxmail.com>
 * @version :    v1.0
 * =======================================================
 */
 
class safe {
    const getfilter="'|(and|or)\b.+?(>|<|=|in|like)|\/\*.+?\*\/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
    const postfilter="\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|\/\*.+?\*\/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
    const cookiefilter="\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|\/\*.+?\*\/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
 
    public function __construct() {
 
    }
 
    public function initLogHacker() {
         
        foreach($_GET as $key=>$value){
            $this->StopAttack($key,$value,self::getfilter);
            $_GET[$key] = $this->safe_replace($value);
            $_GET[$key] = $this->remove_xss($_GET[$key]);
        }
         
        foreach($_COOKIE as $key=>$value){
            $this->StopAttack($key,$value,self::cookiefilter);
        }
         
        foreach($_POST as $key=>$value){
            if (!is_array($value)) {
                $_POST[$key] = $this->trim_script($value);
            }
            $this->StopAttack($key,$value,self::postfilter);
        }
    }
     
    private function StopAttack($StrFiltKey,$StrFiltValue,$ArrFiltReq){
        if(is_array($StrFiltValue)) {
            $StrFiltValue=implode($StrFiltValue);
        }     
        if (preg_match("/".$ArrFiltReq."/is",$StrFiltValue)==1){
            $attackStr = "<br><br>SubmitIP:".$_SERVER["REMOTE_ADDR"]."<br>SubmitTime:".strftime("%Y-%m-%d %H:%M:%S")."<br>SubmitPage:".$_SERVER["PHP_SELF"]."<br>SubmitMethod:".$_SERVER["REQUEST_METHOD"]."<br>SubmitParams:".$StrFiltKey."<br>SubmitData:".$StrFiltValue;
            exit("Illegal operation:" . $attackStr);
        }
    }
     
    /**
     * 安全过滤函数
     *
     * @param $string
     * @return string
     */
    private 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);
        $string = str_replace('or', '', $string);
        $string = str_replace('insert', '', $string);
        $string = str_replace('update', '', $string);
        $string = str_replace('delete', '', $string);
        $string = str_replace('and', '', $string);
        $string = str_replace('union', '', $string);
        $string = str_replace('load_file', '', $string);
        $string = str_replace('outfil', '', $string);
        $string = str_replace('TRUNCATE', '', $string);
        return $string;
    }
     
    /**
     * 转义 javascript 代码标记
     *
     * @param $str
     * @return mixed
     */
    private function trim_script($str) {
        if (is_array($str)) {
            foreach ($str as $key => $val) {
                $str[$key] = trim_script($val);
            }
        } else {
            $str = preg_replace('/<([/]?)script([^>]*?)>/si', '<\1script\2>', $str);
            $str = preg_replace('/<([/]?)iframe([^>]*?)>/si', '<\1iframe\2>', $str);
            $str = preg_replace('/<([/]?)frame([^>]*?)>/si', '<\1frame\2>', $str);
            $str = preg_replace('/]]>/si', ']] >', $str);
        }
        return $str;
    }
     
    /**
     * 防止XSS攻击,用在表单textarea中内容过滤较多
     *
     * @param $str
     * @return mixed
     */
    private function remove_xss($val) {
        $val = preg_replace('/([-,-,-])/', '', $val);
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|'\';
        for ($i = 0; $i < strlen($search); $i++) {
            $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
            $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
        }
 
        $ra1 = array(
            'javascript',
            'vbscript',
            'expression',
            'applet',
            'meta',
            'xml',
            'blink',
            'link',
            'style',
            'script',
            'embed',
            'object',
            'iframe',
            'frame',
            'frameset',
            'ilayer',
            'layer',
            'bgsound',
            'title',
            'base'
            );
            $ra2 = 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($ra1, $ra2);
 
            $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{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;
                    }
                }
            }
            return $val;
    }
}
 
?>
登录后复制

safe.class.php

phpapp威客系统
phpapp威客系统

PHPAPP 是EDOOG 旗下新产品,全球领先的网站应用系统。PHPAPP 全球网站应用的开创者,独创系统核心长期提供丰富网站应用程序,专为站长企业打造盈利应用。 威客交易程序 站长赚钱首选程序!!!安全: 独创全ID URL直接屏蔽SQL注入问题,提供过虑系统对提交的数据进行过虑。高效: 独创 AVC ( 应用Application 视图 View 和控制Controller ) 面向过程垂直

phpapp威客系统 1
查看详情 phpapp威客系统
<?php
 
defined('TC_CMS') or exit('Access Denied');
 
/**
 * TC_CMS
 * =======================================================
 * 版权所有 (C) 2010-2020 www.teamcen.com,并保留所有权利。
 * 网站地址: http://www.teamcen.com
 * Q Q: 9877633
 * -------------------------------------------------------
 *
 * @author :     milkcy <milkcy@foxmail.com>
 * @version :    v1.0
 * =======================================================
 */
 
class safe {
    const getfilter="'|(and|or)\b.+?(>|<|=|in|like)|\/\*.+?\*\/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
    const postfilter="\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|\/\*.+?\*\/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
    const cookiefilter="\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|\/\*.+?\*\/|<\s*script\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";
 
    public function __construct() {
 
    }
 
    public function initLogHacker() {
         
        foreach($_GET as $key=>$value){
            $this->StopAttack($key,$value,self::getfilter);
            $_GET[$key] = $this->safe_replace($value);
            $_GET[$key] = $this->remove_xss($_GET[$key]);
        }
         
        foreach($_COOKIE as $key=>$value){
            $this->StopAttack($key,$value,self::cookiefilter);
        }
         
        foreach($_POST as $key=>$value){
            if (!is_array($value)) {
                $_POST[$key] = $this->trim_script($value);
            }
            $this->StopAttack($key,$value,self::postfilter);
        }
    }
     
    private function StopAttack($StrFiltKey,$StrFiltValue,$ArrFiltReq){
        if(is_array($StrFiltValue)) {
            $StrFiltValue=implode($StrFiltValue);
        }     
        if (preg_match("/".$ArrFiltReq."/is",$StrFiltValue)==1){
            $attackStr = "<br><br>SubmitIP:".$_SERVER["REMOTE_ADDR"]."<br>SubmitTime:".strftime("%Y-%m-%d %H:%M:%S")."<br>SubmitPage:".$_SERVER["PHP_SELF"]."<br>SubmitMethod:".$_SERVER["REQUEST_METHOD"]."<br>SubmitParams:".$StrFiltKey."<br>SubmitData:".$StrFiltValue;
            exit("Illegal operation:" . $attackStr);
        }
    }
     
    /**
     * 安全过滤函数
     *
     * @param $string
     * @return string
     */
    private 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);
        $string = str_replace('or', '', $string);
        $string = str_replace('insert', '', $string);
        $string = str_replace('update', '', $string);
        $string = str_replace('delete', '', $string);
        $string = str_replace('and', '', $string);
        $string = str_replace('union', '', $string);
        $string = str_replace('load_file', '', $string);
        $string = str_replace('outfil', '', $string);
        $string = str_replace('TRUNCATE', '', $string);
        return $string;
    }
     
    /**
     * 转义 javascript 代码标记
     *
     * @param $str
     * @return mixed
     */
    private function trim_script($str) {
        if (is_array($str)) {
            foreach ($str as $key => $val) {
                $str[$key] = trim_script($val);
            }
        } else {
            $str = preg_replace('/<([/]?)script([^>]*?)>/si', '<\1script\2>', $str);
            $str = preg_replace('/<([/]?)iframe([^>]*?)>/si', '<\1iframe\2>', $str);
            $str = preg_replace('/<([/]?)frame([^>]*?)>/si', '<\1frame\2>', $str);
            $str = preg_replace('/]]>/si', ']] >', $str);
        }
        return $str;
    }
     
    /**
     * 防止XSS攻击,用在表单textarea中内容过滤较多
     *
     * @param $str
     * @return mixed
     */
    private function remove_xss($val) {
        $val = preg_replace('/([-,-,-])/', '', $val);
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|'\';
        for ($i = 0; $i < strlen($search); $i++) {
            $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
            $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
        }
 
        $ra1 = array(
            'javascript',
            'vbscript',
            'expression',
            'applet',
            'meta',
            'xml',
            'blink',
            'link',
            'style',
            'script',
            'embed',
            'object',
            'iframe',
            'frame',
            'frameset',
            'ilayer',
            'layer',
            'bgsound',
            'title',
            'base'
            );
            $ra2 = 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($ra1, $ra2);
 
            $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{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;
                    }
                }
            }
            return $val;
    }
}
 
?>
登录后复制
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号