如何正确的理解
在PHP中默认有一个"魔术引号"的开关, 如果这个开关打开, 从外部转入的$_GET, $_GET, $COOKIE都会PHP转义.
比如:
http://localhost/test.PHP?test=1'
然后在test.PHP输出时自动转义, 输出如下:
var_dump($_GET['test'];
========output=======
string(3) "1'"
所示 ' 号被加入了转义了.但这里有一个问题, 当将这个值输出到网页时会看到满屏的, 这里可以使用另一个函数, stripslashes 可以将去除.
在手册中的PHP转义意思是说推荐不要开启"魔术引号" 因为效率问题, 不这也有一个好处, 就是可以非常安全, 对于我这样的新手来说.
关闭"魔术引号有三个方法, 因为这个是不可以PHP运行进关闭的, 也就是说不可以用ini_set().
1. 对PHP.ini设置.
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
2. 如果对系统无法修改可以使用 .htaccess
PHP_flag magic_quotes_gpc Off
3. 效率最低的PHP转义方法
<ol class="dp-xml"> <li class="alt"><span><span>if (get_magic_quotes_gpc()) { </span></span></li> <li><span>function stripslashes_deep($value) </span></li> <li class="alt"><span>{ </span></li> <li> <span>$</span><span class="attribute">value</span><span> = </span><span class="attribute-value">is_array</span><span>($value) ? </span> </li> <li class="alt"><span>array_map('stripslashes_deep', $value) : </span></li> <li><span>stripslashes($value); </span></li> <li class="alt"><span>return $value; </span></li> <li><span>} </span></li> <li class="alt"> <span>$</span><span class="attribute">_POST</span><span> = </span><span class="attribute-value">array_map</span><span>('stripslashes_deep', $_POST); </span> </li> <li> <span>$</span><span class="attribute">_GET</span><span> = </span><span class="attribute-value">array_map</span><span>('stripslashes_deep', $_GET); </span> </li> <li class="alt"> <span>$</span><span class="attribute">_COOKIE</span><span> = </span><span class="attribute-value">array_map</span><span>('stripslashes_deep', $_COOKIE); </span> </li> <li><span>} </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>
这里还要提到一个关于 SQL语句中有LIKE时对%的处理, 因为addslashes对% _ 是不转义的, 且这两个字符在别的SQL语句也本来也不用转义的, 所以我编了一个函数 like_esc($value), 当有LIKE语句时才使用.
对于输出到网页的先用stripslashes去还要用htmlspecialchars转义一下.
我现在有一个比较懒的PHP转义方法也是对所有转入的都转义.
<ol class="dp-xml"> <li class="alt"><span><span>if (!get_magic_quotes_gpc()) { </span></span></li> <li><span>function addslashes_deep($value) </span></li> <li class="alt"><span>{ </span></li> <li> <span>$</span><span class="attribute">value</span><span> = </span><span class="attribute-value">is_array</span><span>($value) ? array_map('addslashes_deep', $value) : addslashes($value); </span> </li> <li class="alt"><span>return $value; </span></li> <li><span>} </span></li> <li class="alt"> <span>$</span><span class="attribute">_POST</span><span> = </span><span class="attribute-value">array_map</span><span>('addslashes_deep', $_POST); </span> </li> <li> <span>$</span><span class="attribute">_GET</span><span> = </span><span class="attribute-value">array_map</span><span>('addslashes_deep', $_GET); </span> </li> <li class="alt"> <span>$</span><span class="attribute">_COOKIE</span><span> = </span><span class="attribute-value">array_map</span><span>('addslashes_deep', $_COOKIE); </span> </li> <li><span>} </span></li> </ol>