WordPress中的魔术引号,以及如何摆脱它们

许多开发人员不知道的一件事是,WordPress自动将魔术引号添加到请求变量中。这意味着所有引号,反斜杠和空字节字符都将以反斜杠转义。

即使您在php.ini中禁用了魔术引号,WordPress仍将反引号应用于$ _GET,$ _ POST,$ _ COOKIE和其他超全局变量。如果您发现输入数据中出现意外的斜线,这就是原因。

启用魔术引号的功能称为wp_magic_quotes()。在WordPress完成加载插件后不久,它就在中声明/wp-includes/load.php并调用了/wp-settings.php

/**
 * Add magic quotes to $_GET, $_POST, $_COOKIE, and $_SERVER.
 *
 * Also forces $_REQUEST to be $_GET + $_POST. If $_SERVER, $_COOKIE,
 * or $_ENV are needed, use those superglobals directly.
 *
 * @access private
 * @since 3.0.0
 */
function wp_magic_quotes() {
    // If already slashed, strip.
    if ( get_magic_quotes_gpc() ) {
        $_GET    = stripslashes_deep( $_GET    );
        $_POST   = stripslashes_deep( $_POST   );
        $_COOKIE = stripslashes_deep( $_COOKIE );
    }
 
    // Escape with wpdb.
    $_GET    = add_magic_quotes( $_GET    );
    $_POST   = add_magic_quotes( $_POST   );
    $_COOKIE = add_magic_quotes( $_COOKIE );
    $_SERVER = add_magic_quotes( $_SERVER );
 
    // Force REQUEST to be GET + POST.
    $_REQUEST = array_merge( $_GET, $_POST );
}

那么,如何访问干净,未转义的数据呢?不幸的是,不编辑核心文件就不可能完全关闭WordPress魔术引号。但是,由于WordPress 所有插件加载添加了引号,因此您可以在插件加载时(或在“ plugins_loaded”操作中)简单地获取未修改的变量,并存储本地副本供自己使用。这是一个例子:

class MyExamplePlugin {
    //Local copies of the PHP superglobals.
    private $get;
    private $post;
    private $cookie;
 
    public function __construct() {
        /* ... Other plugin code ... */
 
        add_action('plugins_loaded', array($this, 'captureRequestVars'));
    }
 
    public function captureRequestVars() {
        //Store the original GET and POST data + cookies.
        $this->get = $_GET;
        $this->post = $_POST;
        $this->cookie = $_COOKIE;
 
        //If magic quotes are actually enabled in PHP,
        //we'll need to remove the slashes.
        if ( get_magic_quotes_gpc() ) {
            $this->get    = stripslashes_deep($this->get);
            $this->post   = stripslashes_deep($this->post);
            $this->cookie = stripslashes_deep($this->cookie);
        }
    }
 
    public function doSomethingWithInput() {
        /* ... */
 
        //Use the internal copy of $_GET.
        $something = $this->get['something'];
 
        /* ... */
    }
}
 
$myExamplePlugin = new MyExamplePlugin();

现在您可能会想知道:为什么可以继续按常规使用它们并仅stripslashes()在任何输入数据上运行时,复制内置PHP变量会遇到所有麻烦?有以下几个原因:

  • 迟早,您将忘记给stripslashes()某个地方打电话。这可能导致难以发现的错误。
  • 代码重复。当您可以将反斜杠代码放在一个地方时,为什么还要将其扩展到整个代码库中呢?
  • 前向兼容性。如果WordPress团队决定停止仿效此已弃用的PHP错误功能,则不加选择地应用于stripslashes()所有输入数据的插件和主题将突然中断。

就是说,我不会指望WordPress很快就会放弃这一“功能”。这是向后兼容的问题,有时WordPress似乎认为兼容性比鼓励良好的编程习惯更重要。

来源于: https://w-shadow.com/blog/2012/11/13/wordpress-magic-quotes/

插件

TablePress - wordpress表格插件

2020-3-25 14:10:48

插件

Pro Bulk Watermark - wordpress图像水印插件

2020-1-10 22:14:58

⚠️
Npcink上的部份代码及教程来源于互联网,仅供网友学习交流,若您喜欢本文可附上原文链接随意转载。
无意侵害您的权益,请发送邮件至 1355471563#qq.com 或点击右侧 私信:Muze 反馈,我们将尽快处理。
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索