許多開發人員不知道的一件事是,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/