防sql注入代码类

转载自PHP中文网
通过对get,post,cookie参数的过滤来达到sql注入

<?php
/**
 * 防止sql注入.
 * User: Pengfan
 * Date: 2018/10/27
 * Time: 9:43
 */
class  sqlSafe
{

    //日志目录
    const CACHE_PATH = '''';

    //get敏感字正则
    private $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)";

    //post敏感字正则
    private $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)";

    //cookie敏感字正则
    private $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() {

        foreach($_GET as $key=>$value){$this->stopattack($key,$value,$this->getFilter);}

        foreach($_POST as $key=>$value){$this->stopattack($key,$value,$this->postFilter);}

        foreach($_COOKIE as $key=>$value){$this->stopattack($key,$value,$this->cookieFilter);}

    }


    //过滤
    public function stopattack($StrFilterKey, $StrFilterValue, $ArrFilterReq){

        if(is_array($StrFilterValue)) $StrFilterValue = implode($StrFilterValue);

        if (preg_match("/".$ArrFilterReq."/is",$StrFilterValue) == 1)
        {
            //log日志
            $logsStr = $_SERVER["REMOTE_ADDR"]."    ".strftime("%Y-%m-%d %H:%M:%S")."    ";

            $logsStr .= $_SERVER["PHP_SELF"]."    ".$_SERVER["REQUEST_METHOD"]."    ".$StrFilterKey."    ".$StrFilterValue;

            $this->writeslog($logsStr);

            $this->showmsg(''您提交的参数非法,系统已记录您的本次操作!'');

        }

    }



    //返回信息
    public function showmsg($msg = '''')
    {
        header("Content-type:application/json;charset=utf-8");
        $data[''code''] = -1;
        $data[''msg''] = $msg;
        $data[''data''] = new \\stdClass();
        echo json_decode($data);
        die();
    }


    //写入日志
    public function writeslog($log){

        $log_path = static::CACHE_PATH.''logs''.DIRECTORY_SEPARATOR.''sql_log.txt'';

        $ts = fopen($log_path,"a+");

        fputs($ts,$log."\\r\\n");

        fclose($ts);

    }




}
已有 2 条评论
  1. 22 22

    我的测试

    alert(123)

添加新评论