2009-12-01 31 views
1

我用下面的從我接觸的形式清理輸入:安全電子郵件的形式,頭注入查詢

<?php 
$name = strip_tags(stripslashes($_POST['name'])); 
//this is repeated for several other fields, then: 

if(isInjected($name)) { die(); } 
/* see isInjected function below */ 

// send the mail 
?> 

我使用這個功能:

<?php 
    /* function from http://phpsense.com/php/php-mail.html */ 
    function isInjected($str) { 
     $injections = array('(\n+)', 
     '(\r+)', 
     '(\t+)', 
     '(%0A+)', 
     '(%0D+)', 
     '(%08+)', 
     '(%09+)' 
     ); 
     $inject = join('|', $injections); 
     $inject = "/$inject/i"; 
     if(preg_match($inject,$str)) { 
      return true; 
     } 
     else { 
      return false; 
     } 
    } 
?> 

這是足以清理我的聯繫表格?

謝謝。

回答

1

它似乎prettey體面和更好的平均inputvalidation。 Personanlly我也喜歡處理輸入類型。在我的基礎控制器中,我有幾個函數來檢查輸入是否是有效的出生日期,emailaddress等。如果您將這種驗證添加到您現有的驗證中,那麼您正好處理IMO。

3

作爲一個側面說明,代碼有點臃腫。它可以很容易地修剪:

/* function from http://phpsense.com/php/php-mail.html */ 
function isInjected($str) { 
    $inject = "/(\r|\t|%0A|%0D|%08|%09)+/i"; 
    return (preg_match($inject, $str) > 0); 
} 
+0

非常好,謝謝。 – Met 2009-12-01 13:07:57

+0

爲什麼'(preg_match($ inject,$ str)> 0)''? :) – chelmertz 2009-12-01 13:23:57

+1

只是我的個人喜好。這可能源於當我使用三元運算符來確定函數參數或者在一個連接字符串內部並且需要這些元素時。 – 2009-12-01 17:17:48