<?php

class sqlsafe {


    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)";
    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)';
    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() {

    }


	public function filter ($log=false){

        foreach($_GET as $key => $value){
			$this -> stopattack ($key,$value,$this->getfilter,'GET',$log);
		}

        foreach($_POST as $key => $value){
			$this -> stopattack ($key,$value,$this->postfilter,'POST',$log);
		}

		foreach($_COOKIE as $key => $value){
			$this -> stopattack ($key,$value,$this->cookiefilter,'COOKIE',$log);
		}

	}


    /**
     * 参数检查并写日志
     */
    public function stopattack ($StrFiltKey, $StrFiltValue, $ArrFiltReq, $Type, $log){

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

		if (preg_match ('/'.$ArrFiltReq.'/is',$StrFiltValue) == 1){
            if ($log) $this -> writeslog($Type.'  ->  '.$StrFiltKey.'  ->  '.$StrFiltValue);

            prompt ('<p>AnYueKeJi tip you:</p><p>Find the SQL malicious code injection, has been blocked:</p><p>注入类型：'.$Type.', 注入参数：'.$StrFiltKey.', 注入数据：'.htmlentities ($StrFiltValue).'</p><p style="color: red;">你的信息已被系统记录并发送至当地工信局，若你是有意的，小心被捕入狱。</p>','暗月科技 -&rsaquo; 成功拦截'.$Type.'注入代码');
			exit;
        }

    }


    /**
     * SQL注入日志
     */
    public function writeslog ($log){
        file_put_contents (dirname(__FILE__).'\\Sql_Log.txt',"\r\n".'[ '.$this->get_ip ().' @ '.time().' ]  '.$log,FILE_APPEND);
    }


    /**
     * 获取用户真实IP
     */
	public function get_ip (){

		if (@$_SERVER['HTTP_X_FORWARDED_FOR'])
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else if (@$_SERVER['HTTP_CLIENT_IP'])
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		else if (@$_SERVER['REMOTE_ADDR'])
			$ip = $_SERVER['REMOTE_ADDR'];
		else if (@getenv('HTTP_X_FORWARDED_FOR'))
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		else if (@getenv('HTTP_CLIENT_IP'))
			$ip = getenv('HTTP_CLIENT_IP');
		else if (@getenv('REMOTE_ADDR'))
			$ip = getenv('REMOTE_ADDR');
		else
			$ip = 'Unknown';
		return $ip;

	}


}


