许多开发人员不知道的一件事是,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/