許多開發(fā)人員不知道的一件事是,WordPress自動將魔術(shù)引號添加到請求變量中。這意味著所有引號,反斜杠和空字節(jié)字符都將以反斜杠轉(zhuǎn)義。
即使您在php.ini中禁用了魔術(shù)引號,WordPress仍將反引號應(yīng)用于$ _GET,$ _ POST,$ _ COOKIE和其他超全局變量。如果您發(fā)現(xiàn)輸入數(shù)據(jù)中出現(xiàn)意外的斜線,這就是原因。
啟用魔術(shù)引號的功能稱為wp_magic_quotes()
。在WordPress完成加載插件后不久,它就在中聲明/wp-includes/load.php
并調(diào)用了/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 );
}
那么,如何訪問干凈,未轉(zhuǎn)義的數(shù)據(jù)呢?不幸的是,不編輯核心文件就不可能完全關(guān)閉WordPress魔術(shù)引號。但是,由于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();
現(xiàn)在您可能會想知道:為什么可以繼續(xù)按常規(guī)使用它們并僅stripslashes()
在任何輸入數(shù)據(jù)上運行時,復(fù)制內(nèi)置PHP變量會遇到所有麻煩?有以下幾個原因:
- 遲早,您將忘記給
stripslashes()
某個地方打電話。這可能導(dǎo)致難以發(fā)現(xiàn)的錯誤。 - 代碼重復(fù)。當(dāng)您可以將反斜杠代碼放在一個地方時,為什么還要將其擴(kuò)展到整個代碼庫中呢?
- 前向兼容性。如果WordPress團(tuán)隊決定停止仿效此已棄用的PHP錯誤功能,則不加選擇地應(yīng)用于
stripslashes()
所有輸入數(shù)據(jù)的插件和主題將突然中斷。
就是說,我不會指望WordPress很快就會放棄這一“功能”。這是向后兼容的問題,有時WordPress似乎認(rèn)為兼容性比鼓勵良好的編程習(xí)慣更重要。
來源于: https://w-shadow.com/blog/2012/11/13/wordpress-magic-quotes/