php簡(jiǎn)單實(shí)現(xiàn)sql防注入的方法

字號(hào):


    本文實(shí)例講述了php簡(jiǎn)單實(shí)現(xiàn)sql防注入的方法。分享給大家供大家參考,具體如下:
    這里沒(méi)有太多的過(guò)濾,主要是針對(duì)php和mysql的組合。
    一般性的防注入,只要使用php的 addslashes 函數(shù)就可以了。
    以下是一段copy來(lái)的代碼:
    PHP代碼:
    $_POST = sql_injection($_POST);
    $_GET = sql_injection($_GET);
    function sql_injection($content)
    {
    if (!get_magic_quotes_gpc()) {
    if (is_array($content)) {
    foreach ($content as $key=>$value) {
    $content[$key] = addslashes($value);
    }
    } else {
    addslashes($content);
    }
    }
    return $content;
    }
    做系統(tǒng)的話,可以用下面的代碼,也是copy來(lái)的。
    PHP代碼:
    function inject_check($sql_str) {
     return eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);  // 進(jìn)行過(guò)濾
    }
    function verify_id($id=null) {
     if (!$id) { exit('沒(méi)有提交參數(shù)!'); }  // 是否為空判斷
     elseif (inject_check($id)) { exit('提交的參數(shù)非法!'); }  // 注射判斷
     elseif (!is_numeric($id)) { exit('提交的參數(shù)非法!'); }  // 數(shù)字判斷
     $id = intval($id);  // 整型化
     return $id;
    }
    function str_check( $str ) {
     if (!get_magic_quotes_gpc()) {  // 判斷magic_quotes_gpc是否打開(kāi)
      $str = addslashes($str);  // 進(jìn)行過(guò)濾
     }
     $str = str_replace("_", "\_", $str);  // 把 '_'過(guò)濾掉
     $str = str_replace("%", "\%", $str);  // 把 '%'過(guò)濾掉
     return $str;
    }
    function post_check($post) {
     if (!get_magic_quotes_gpc()) {  // 判斷magic_quotes_gpc是否為打開(kāi)
      $post = addslashes($post);  // 進(jìn)行magic_quotes_gpc沒(méi)有打開(kāi)的情況對(duì)提交數(shù)據(jù)的過(guò)濾
     }
     $post = str_replace("_", "\_", $post);  // 把 '_'過(guò)濾掉
     $post = str_replace("%", "\%", $post);  // 把 '%'過(guò)濾掉
     $post = nl2br($post);  // 回車(chē)轉(zhuǎn)換
     $post = htmlspecialchars($post);  // html標(biāo)記轉(zhuǎn)換
     return $post;
    }
    希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。