在php中我們常會使用到stripslashes與addslashes了, 下面我來詳細的介紹stripslashes與addslashes使用方法與它們之間的區別.
addslashes
addslashes() 函數在指定的預定義字符前添加反斜杠.
這些預定義字符是:
•單引號 (')
•雙引號 (")
•反斜杠 ()
•NULL
在本例中,我們要向字符串中的預定義字符添加反斜杠:
注釋:默 認情況下,PHP 指令 magic_quotes_gpc 為 on,對所有的 GET、POST 和 COOKIE 數據自動運行 addslashes().不要對已經被 magic_quotes_gpc 轉義過的字符串使用 addslashes(),因為這樣會導致雙層轉義.遇到這種情況時可以使用函數 get_magic_quotes_gpc() 進行檢測.
實例代碼:
- /**
- * 判斷是否用addslashes()處理
- *
- * @param String $str
- *
- */
- function str_addslashes($str, $db_type='mysql') {
- if(get_magic_quotes_gpc()){
- switch($db_type){
- case "access":
- $str = stripslashes($str);
- $str = str_replace("'","''",$str);
- break;
- }
- }else {
- switch($db_type){
- case "mysql":
- $str = addslashes($str);
- break;
- case "access":
- $str = str_replace("'","''",$str);
- break;
- }
- }
- return $str;
- }
自定義函數str_addslashes說明:如果我們在提交過程中不知道magic_quotes_gpc是否打開的情況下,可采取如此方式進行處理,為on時mysql數據庫不做處理,而access數據庫依然要先去掉,再將單引號替換為雙引號.為off時mysql數據庫加上
stripslashes()
stripslashes() 函數刪除由 addslashes() 函數添加的反斜杠.
實例代碼:
- //提交數據,或者變量準備:
- $Content=addslashes(”這里面是數據,不管有沒單引號或者還是變量”);
- //插入數據到數據庫,代碼省略
- //開始顯示數據
- $Content=”從數據庫讀取的數據”;
- if(get_magic_quotes_gpc()){
- $Content=stripslashes($Content);
- }
- echo $Content;
區別總結
當magic_quotes_gpc = On時,使用了addslashes()處理后的數據在數據庫中將以’形式保存,如果此時直接輸出的話,就會發現比自己期待的內容多了個,因此stripslashes()出場了,它能把去掉(區別于str_replace(””, “”,$Str)).
當magic_quotes_gpc = Off時,使用了addslashes()處理后的數據在數據庫中將以’形式保存,沒有上面說的有的問題,addslashes()起到插入數據不出錯的作用,如果此時直接輸出的話,數據正常.不需要再用stripslashes().addslashes()和stripslashes()正好是相反的,直接記憶:addslashes()加個,stripslashes()去個
新聞熱點
疑難解答