2012-05-23 62 views
1

如果我正在清理從表格到mysql表格的代碼,這是否會訣竅?應該/將要輸入的數據將是學校科目和教授的姓氏/名字......關於如何執行此操作的任何其他建議?爲MySQL表格消毒表格數據

/* 
Sanitize() function removes any potential threat from the 
data submitted. Prevents email injections or any other hacker attempts. 
if $remove_nl is true, newline chracters are removed from the input. 
*/ 
function Sanitize($str,$remove_nl=true) 
{ 
    $str = $this->StripSlashes($str); 

    if($remove_nl) 
    { 
     $injections = array('/(\n+)/i', 
      '/(\r+)/i', 
      '/(\t+)/i', 
      '/(%0A+)/i', 
      '/(%0D+)/i', 
      '/(%08+)/i', 
      '/(%09+)/i' 
      ); 
     $str = preg_replace($injections,'',$str); 
    } 

    return $str; 
}  
function StripSlashes($str) 
{ 
    if(get_magic_quotes_gpc()) 
    { 
     $str = stripslashes($str); 
    } 
    return $str; 
} 

回答

0

爲什麼不使用mysql_real_escape_string()逃避所有可能導致問題的潛在角色?除了內置之外,它還可以證明MySQL自己的mysql_real_escape_string,因此您知道您將始終掌握已安裝的數據庫需要轉義的內容。

+0

會做。我已經對這個問題做了一些研究,但是如果這是正確的方法,我不確定給出上下文(意思是我試圖過濾的數據)。非常感謝John! –

1

我推薦PHP的PDO class。你會做這樣的事情:

try 
{ 
    $sql ='INSERT INTO whatever(a,b,c) VALUES(:a,:b:c); 
    //or if you prefer... 
    $sql ='INSERT INTO whatever(a,b,c) VALUES(?,?,?); 
    $stmt = db::db()->prepare($sql); 
    $stmt->execute(array(123,234,345)); 
} 
catch(PDOException $e){library::sql_error($e,$sql);} 
0

試試這個:

function sanatize($value) { 

      $value = preg_replace("~" . "[^a-zA-Z0-9\-\_\.]" . "~iU", "", $value); 
      return $value; 
    } 
1

感謝大家抽出寶貴時間來幫助。我使用了preg_replace函數,該函數將字符限制爲我想要人們使用的:preg_replace("~" . "[^a-zA-Z0-9\-\_\.\ ]" . "~iU", "", $string)。我也使用mysql_real_escape_string,所以我在發送到數據庫之前先進行兩級過濾。