2010-04-30 92 views
4

什麼是一些很好的PHP html(輸入)消毒劑?PHP輸入消毒劑?

最好是,如果有東西是內置的 - 我想給我們。

UPDATE

每請求,通過評論,輸入應允許HTML(顯然防止XSS & SQL注入等)。

+0

我覺得這個問題需要一些更多的信息;你是否在談論允許用戶直接輸入HTML,並對其進行消毒以去除像'

0

我一直使用PHP的和addslashes()和stripslashes()函數的功能,但我也只是看到內置filter_var()函數(link)。看起來好像有很多built-in filters

+0

爲什麼你使用PHP的addslashes()和stripslashes()函數? – 2010-04-30 14:27:17

0

如果你想運行使用假設$_GET['user']查詢一個很好的解決辦法是使用mysql_real_escape_string()做這樣的事情:

<?php 

    $user = mysql_real_escape_string($_GET['user']); 
    $SQL = "SELECT * FROM users WHERE username = '$name'"; 

    //run $SQL now 
    ... 
?> 

如果你想將文本存儲在數據庫中,然後打印出來在網頁上,可以考慮使用htmlentities

[編輯],還是awshepard說,你可以使用addslashes()stripslashes()功能[/編輯]

這裏是一個小例子消毒的,當談到防止XSS攻擊:

<?php 
    $str = "A 'quote' is <b>bold</b>"; 

    //Outputs: A 'quote' is <b>bold</b> 
    echo $str; 

    // Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt; 
    echo htmlentities($str); 

    // Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt; 
    echo htmlentities($str, ENT_QUOTES); 
?> 
+0

你的MySQL示例不會打開你SQL注入(你的例子應該使用Prepared Statements) – TeddyN 2010-04-30 15:45:26

+0

我沒有使用Prepared Statements,我使用了mysql_real_escape_string(),就像在我的PHP代碼中一樣,直到現在我無法找到一種方法來利用我寫的代碼。也許我沒有看到可能的攻擊向量,可以繞過mysql_real_escape_string(),所以如果你有一個例子,請讓我知道我總是想學到新東西 – 2010-04-30 17:03:12

+0

@Dr Optix,StackOverflow確認mysql_real_escape_string()並不總是防止SQL注入 - > http: //stackoverflow.com/questions/1220182/does-mysql-real-escape-string-fully-protect-against-sql-injection – TeddyN 2010-04-30 21:48:14

0

使用

$input_var=sanitize_input($_POST); 

功能低於,幾乎消毒寄託都u需要

function sanitize($var, $santype = 1){ 
    if ($santype == 1) {return strip_tags($var);} 
    if ($santype == 2) {return htmlentities(strip_tags($var),ENT_QUOTES,'UTF-8');} 
    if ($santype == 3) 
    { 
     if (!get_magic_quotes_gpc()) { 
     return addslashes(htmlentities(strip_tags($var),ENT_QUOTES,'UTF-8')); 
     } 
     else { 
     return htmlentities(strip_tags($var),ENT_QUOTES,'UTF-8'); 
     } 
    } 
    } 

function sanitize_input($input,$escape_mysql=false,$sanitize_html=true, 
      $sanitize_special_chars=true,$allowable_tags='<br><b><strong><p>') 
    { 
     unset($input['submit']); //we use 'submit' variable for all of our form 

     $input_array = $input; 

     //array is not referenced when passed into foreach 
     //this is why we create another exact array 
     foreach ($input as $key=>$value) 
     { 
     if(!empty($value)) 
     { 
     $input_array[$key]=strtolower($input_array[$key]); 
     //stripslashes added by magic quotes 
     if(get_magic_quotes_gpc()){$input_array[$key]=sanitize($input_array[$key]);} 

     if($sanitize_html){$input_array[$key] = strip_tags($input_array[$key],$allowable_tags);} 

     if($sanitize_special_chars){$input_array[$key] = htmlspecialchars($input_array[$key]);}  

     if($escape_mysql){$input_array[$key] = mysql_real_escape_string($input_array[$key]);} 
     } 
     } 

     return $input_array; 

    } 

請記住:它不會淨化多維數組,您需要遞歸修改它。