您的位置:首页 > 编程语言 > PHP开发

PHP中get_magic_quotes_gpc()函数是内置的函数,这个函数的作用就是得到php.ini设置中magic_quotes_gpc选项的值。

2017-09-23 09:37 736 查看
在PHP中get_magic_quotes_gpc()函数是内置的函数,这个函数的作用就是得到php.ini设置中magic_quotes_gpc选项的值。

那么就先说一下magic_quotes_gpc选项:

如果magic_quotes_gpc=On,PHP解析器就会自动为post、get、cookie过来的数据增加转义字符“\”,以确保这些数据不会引起程序,特别是数据库语句因为特殊字符引起的污染而出现致命的错误。

在magic_quotes_gpc=On的情况下,如果输入的数据有

单引号(’)、双引号(”)、反斜线(\)与 NUL(NULL字符)等字符都会被加上反斜线。这些转义是必须的,如果这个选项为off,那么我们就必须调用addslashes这个函数来为字符串增加转义。

正是因为这个选项必须为On,但是又让用户进行配置的矛盾,在PHP6中删除了这个选项,一切的编程都需要在magic_quotes_gpc=Off下进行了。在这样的环境下如果不对用户的数据进行转义,后果不仅仅是程序错误而已了。同样的会引起数据库被注入攻击的危险。所以从现在开始大家都不要再依赖这个设置为On了,以免有一天你的服务器需要更新到PHP6而导致你的程序不能正常工作。

当magic_quotes_gpc=On的时候,函数get_magic_quotes_gpc()就会返回1

当magic_quotes_gpc=Off的时候,函数get_magic_quotes_gpc()就会返回0

自 php5.4起这个函数已经被移除,所以手动转义字符成了必须的。

$magic_quote = get_magic_quotes_gpc();

if(empty($magic_quote)) {

        $_GET = saddslashes($_GET);

        $_POST = saddslashes($_POST);

}

function saddslashes($string) {

        if(is_array($string)) {

                foreach($string as $key => $val) {

                        $string[$key] = saddslashes($val);

                }

        } else {

                $string = addslashes($string);

        }

        return $string;

}

手册中:

<?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')";

?>

Example #2 Using stripslashes() on an array on

<http://www.php.net/manual/en/function.stripslashes.php>:

<?php

function stripslashes_deep($value)

{

    $value = is_array($value) ?

                array_map('stripslashes_deep', $value) :

                stripslashes($value);

    return $value;

}

?>

This gives:

<?php

if((function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())    || (ini_get('magic_quotes_sybase') && (strtolower(ini_get('magic_quotes_sybase'))!="off")) ){

    stripslashes_deep($_GET);

    stripslashes_deep($_POST);

    stripslashes_deep($_COOKIE);

}

?>
http://php.net/manual/zh/function.get-magic-quotes-gpc.php
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: