2009年10月5日 星期一

PHP的Data Filtering初步整理

為了過濾使用者輸入的資料,PHP 5.2.0後就有filter extension可用,主要分成二種: validation和sanitization。validation是過濾資料形態是否為email, ip, url或為int, float, boot...等。sanitization是會自動把不該有的字元移除。不過drupal的討論裡看到用filter_var($value, FILTER_VALIDATE_URL)會有很多錯誤。

相關的函式:
htmlspecialchars - 轉換HTML的特別字元
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<' '>' (greater than) becomes '>'

htmlentities - 全部字元都轉換

差別:

$str = "test>ä";
echo $str; //test>ä
echo htmlentities($str); //test&gt;&Atilde;&curren;
echo htmlspecialchars($str); //test&gt;ä

沒有留言: