php中get_magic_quotes_gpc用法介绍
默认情况下,PHP 指令 magic_quotes_gpc 为 on,它主要是对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。
例子
1. addslashes() 示例
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8209')"><textarea id="copy8209" rows="10" cols="40" style="display: none;"></textarea></td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy8209><?
$str = "Is your name O'reilly?";
// 输出:Is your name O'''reilly?
echo addslashes($str);
?>
返回值
关闭 magic_quotes_gpc 时返回 0,否则是 1。 在 PHP 5.4.O 起将使用返回 FALSE
例
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy2542')"><textarea id="copy2542" rows="10" cols="40" style="display: none;"></textarea></td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy2542><?php
// 如果启用了魔术引号
echo $_POST['lastname']; // O'reilly
echo addslashes($_POST['lastname']); // O\'reilly
// 适用各个 PHP 版本的用法
if (get_magic_quotes_gpc()) {
$lastname = stripslashes($_POST['lastname']);
}
else {
$lastname = $_POST['lastname'];
}
// 如果使用 MySQL
$lastname = mysql_real_escape_string($lastname);
echo $lastname; // O'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>
php.ini:get_magic_quotes_gpc
在php的配置文件中,有个布尔值的设置,就是magic_quotes_runtime,当它打开时,
php的大部分函数自动的给从外部引入的(包括数据库或者文件)数据中的溢出字符加上反
斜线。 当然如果重复给溢出字符加反斜线,那么字符串中就会有多个反斜线,所以这时
就要用set_magic_quotes_runtime()与get_magic_quotes_runtime()设置和检测php.ini
文件中magic_quotes_runtime状态。 为了使自己的程序不管服务器是什么设置都能正常
执行。可以在程序开始用get_magic_quotes_runtime检测该设置的状态决定是否要手工处理
,或者在开始(或不需要自动转义的时候)用set_magic_quotes_runtime(0)关掉该设置。
magic_quotes_gpc设置是否自动为GPC(get,post,cookie)传来的数据中的'"\加上反斜
线。可以用get_magic_quotes_gpc()检测系统设置。如果没有打开这项设置,可以使用
addslashes()函数添加,它的功能就是给数据库查询语句等的需要在某些字符前加上了反
斜线。这些字符是单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。
您可能感兴趣的文章:
php函数get_magic_quotes_gpc
php addslashes 递归实现反斜线引用字符串的方法
set_magic_quotes_runtime()和get_magic_quotes_gpc()的用法举例
php中的get_magic_quotes_gpc()函数
PHP引号前添加反斜杠、去除反斜杠的方法
php引号前添加反斜杠(PHP去除反斜杠)的方法
php防范sql注入的一些代码收集
mysql查询与插入数据单引号的问题分析
PHP中 stripslashes() 函数 和 addslashes() 函数
php中get_magic_quotes_gpc用法介绍