addslashes、mysql_escape_string、htmlentities PHP字串過濾
PHP字串過濾函數說明 addslashes、mysql_escape_string、htmlentities
之前跟大家提到SQL Injection 範例(登入範例) 的時候提到
當使用者要提交資料的時候
一定需要過濾
這次就把手邊常用的過濾字串方式記錄下來讓大家參考
//這一行要讓網頁能順利顯示中文
header("Content-Type:text/html; charset=utf-8");
//首先寫好特定字串
$string1 = "http://tw.yahoo.com/";
$string2 = "This is Stanley's web !!";
$string3 = "hello\ world!!";
$string4 = '_ - 轉換(\) / 轉換(") ';
echo "原始字串的輸出結果:<br>";
echo "string1 = ".$string1;
echo "<br>";
echo "string2 = ".$string2;
echo "<br>";
echo "string3 = ".$string3;
echo "<br>";
echo "string4 = ".$string4;
echo "<br><br>";
//addslashes($string)用法是在系統定義的預設字符中加上反斜線\`;預設字符有雙引號(")、單引號(')、反斜線(\)
$str_addslashes1 = addslashes($string1);
$str_addslashes2 = addslashes($string2);
$str_addslashes3 = addslashes($string3);
$str_addslashes4 = addslashes($string4);
echo "addslashes 函數的輸出結果:<br>";
echo "str_addslashes1 = ".$str_addslashes1;
echo "<br>";
echo "str_addslashes2 = ".$str_addslashes2;
echo "<br>";
echo "str_addslashes3 = ".$str_addslashes3;
echo "<br>";
echo "str_addslashes4 = ".$str_addslashes4;
echo "<br><br>";
//mysql_escape_string($string)用法是在系統定義的預設字符中加上反斜線\`;預設字符有雙引號(")、單引號(')、反斜線(\)
$str_mysql_escape_string1 = mysql_escape_string($string1);
$str_mysql_escape_string2 = mysql_escape_string($string2);
$str_mysql_escape_string3 = mysql_escape_string($string3);
$str_mysql_escape_string4 = mysql_escape_string($string4);
echo "str_mysql_escape_string3 函數的輸出結果:<br>";
echo "str_mysql_escape_string1 = ".$str_mysql_escape_string1;
echo "<br>";
echo "str_mysql_escape_string2 = ".$str_mysql_escape_string2;
echo "<br>";
echo "str_mysql_escape_string3 = ".$str_mysql_escape_string3;
echo "<br>";
echo "str_mysql_escape_string4 = ".$str_mysql_escape_string4;
echo "<br><br>";
//htmlentities($string,編碼方法,輸出時使用的編碼方式)只針對雙引號(")、單引號(')
$str_htmlentities1 = htmlentities($string1);
$str_htmlentities2 = htmlentities($string2);
$str_htmlentities3 = htmlentities($string3);
$str_htmlentities4 = htmlentities($string4,ENT_QUOTES,"UTF-8");
echo "str_htmlentities4 函數的輸出結果:<br>";;
echo "str_htmlentities1 = ".$str_htmlentities1;
echo "<br>";
echo "str_htmlentities2 = ".$str_htmlentities2;
echo "<br>";
echo "str_htmlentities3 = ".$str_htmlentities3;
echo "<br>";
echo "str_htmlentities4 = ".$str_htmlentities4;
這邊跟大家分享自己的經驗
1. 我個人習慣是使用 addslashes(),因為他過濾的最多、最方便
2. mysql_escape_string大多都不建議使用(碎碎念:忘記為什麼了),而是使用mysql_real_escape_string(碎碎念:需要先和資料庫連線,有點麻煩),兩者效果相同,但是在PHP 5.5之後官方已經聲明兩者都不支援使用
3. 如果是為了預防XSS攻擊,使用htmlspecialchars效果會比較好(之後會在另寫文章說明)
4. 如果是簡單的搜索查詢,除了過濾字串之外,也可以檢查型態來防止不當搜索
如果覺得對你有幫助的話. 麻煩幫小弟按個讚哦~
相關文章參考: