在php.ini的配置文件中,有個(gè)布爾值的設(shè)置,就是magic_quotes_runtime,當(dāng)它打開(kāi)時(shí),php的大部分函數(shù)自動(dòng)的給從外部引入的(包括數(shù)據(jù)庫(kù)或者文件)數(shù)據(jù)中的溢出字符加上反斜線。
當(dāng)然如果重復(fù)給溢出字符加反斜線,那么字符串中就會(huì)有多個(gè)反斜線,所以這時(shí)就要用set_magic_quotes_runtime()與get_magic_quotes_runtime()設(shè)置和檢測(cè)php.ini文件中magic_quotes_runtime狀態(tài)。
為了使自己的程序不管服務(wù)器是什么設(shè)置都能正常執(zhí)行。可以在程序開(kāi)始用get_magic_quotes_runtime檢測(cè)設(shè)置狀態(tài)秋決定是否要手工處理,或者在開(kāi)始(或不需要自動(dòng)轉(zhuǎn)義的時(shí)候)用set_magic_quotes_runtime(0)關(guān)掉。
magic_quotes_gpc設(shè)置是否自動(dòng)為GPC(get,post,cookie)傳來(lái)的數(shù)據(jù)中的'"\加上反斜線。可以用get_magic_quotes_gpc()檢測(cè)系統(tǒng)設(shè)置。如果沒(méi)有打開(kāi)這項(xiàng)設(shè)置,可以使用addslashes()函數(shù)添加,它的功能就是給數(shù)據(jù)庫(kù)查詢(xún)語(yǔ)句等的需要在某些字符前加上了反斜線。這些字符是單引號(hào)(')、雙引號(hào)(")、反斜線(\)與 NUL(NULL 字符)。
應(yīng)用實(shí)例見(jiàn)代碼:
PHP代碼
// 去除轉(zhuǎn)義字符
function stripslashes_array($array) {
if (is_array($array)) {
foreach ($array as $k => $v) {
$array[$k] = stripslashes_array($v);
}
} else if (is_string($array)) {
$array = stripslashes($array);
}
return $array;
}
@set_magic_quotes_runtime(0);
// 判斷 magic_quotes_gpc 狀態(tài)
if (@get_magic_quotes_gpc()) {
//如果已經(jīng)打開(kāi)了magic_quotes_gpc,則去掉轉(zhuǎn)義字符,防止雙重轉(zhuǎn)義
$_GET = stripslashes_array($_GET);
$_POST = stripslashes_array($_POST);
$_COOKIE = stripslashes_array($_COOKIE);
}