php的字符串向數據庫進行寫入時,爲避免數據庫錯誤,需要對特殊字符進行轉義,這些特殊字符包括單引號、雙引號、反斜線與null字符。
addslashes()函數會對特殊字符加上轉義字符,返回一個字符串。
$str = "Is your name O'reilly?";
echo addslashes($str); // 輸出:Is your name O\'reilly?
注意:默認情況下,php指令magic_quotes_gpc爲on時,系統會對所有的get、post和cookie數據自動進行
addslashes,不要對已經被magic_quotes_gpc轉義過的字符再次使用addslashes,因爲這樣會導致雙重轉義。可以對magic_quotes_gpc進行檢測以便確定是否需要使用addslashes。
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
stripslashes():該函數是addslashes的反函數,返回一個字符串。
$str = "Is your name O\'reilly?";
echo stripslashes($str); // 輸出:Is your name O'reilly?