学新通技术网

PHP用正则匹配字符串中的特殊字符防SQL注入

Luke 13129 1
PHP用正则匹配字符串中的特殊字符防SQL注入
<?php

/**
 * [用正则匹配字符串中的特殊字符]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://www.swvq.com
 * @param  [data] $str [要匹配的任何数据]
 * @return [type]      [description]
 */
function is_string_regular($str)
{
    $pregs = '/select|insert|update|CR|document|LF|eval|delete|script|alert|\'|\/\*|\#|\--|\ --|\/|\*|\-|\+|\=|\~|\*@|\*!|\$|\%|\^|\&|\(|\)|\/|\/\/|\.\.\/|\.\/|union|into|load_file|outfile/';
    if (is_array($str)) {
        if (TestArray($str) == 1) {
            //一维数组
            foreach ($str as $k => $v) {
                //遍历
                $check = preg_match($pregs, $v);
                if ($check == 1) {
                    $int_arr = array('status' => 1, 'result' => $str, 'message' => '检测含有特殊字符');
                } else {
                    $int_arr = array('status' => 0, 'result' => $str, 'message' => '检测没有特殊字符');
                }
            }
        } else if (TestArray($str) == 2) {
            //二维数组
            foreach ($str as $k => $v) {
                foreach ($v as $ks => $vs) {
                    //遍历
                    $check = preg_match($pregs, $v);
                    if ($check == 1) {
                        $int_arr = array('status' => 1, 'result' => $str, 'message' => '检测含有特殊字符');
                    } else {
                        $int_arr = array('status' => 0, 'result' => $str, 'message' => '检测没有特殊字符');
                    }
                }
            }
        }
    } else if (is_string($str)) {
        //字符串
        $check = preg_match($pregs, $str);
        if ($check == 1) {
            $int_arr = array('status' => 1, 'result' => $str, 'message' => '检测含有特殊字符');
        } else {
            $int_arr = array('status' => 0, 'result' => $str, 'message' => '检测没有特殊字符');
        }
    }
    return $int_arr;
}
/**
 * [TestArray 检测数组是一维还是二维]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://www.swvq.com
 * @param [type] $array [数组]
 */
function TestArray($array)
{
    if (is_array($array)) {
        foreach ($array as $v) {
            if (is_array($v)) {
                $Int_Array = array('Int' => 2, 'Test' => '检测为二维数组');
            } else {
                $Int_Array = array('Int' => 1, 'Test' => '检测为一维数组');
            }
        }
    } else {
        $Int_Array = array('Int' => 3, 'Test' => '检测为不是数组');
    }

    return $Int_Array;
}

本文出至:学新通技术网

标签: