問題描述
我可以看到 wp_nonce_field 在隱藏的字段中生成一個值。
<input type="hidden" id="message-send" name="message-send" value="cabfd9e42d" />
但是 wp_verify_nonce 根本就沒有使用這個值,可能是錯誤的。
看起來它正在使用會話令牌進行驗證。
$expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 );
if ( hash_equals( $expected, $nonce ) )
{ return 1; }
那麼隱藏字段中有一個值屬性是什麼意思?
最佳解決方案
長文慎入
簡而言之,wp_verify_nonce()使用該值,因為它期望該值作為其第一個參數。
wp_verify_nonce()參數
wp_verify_nonce()接收 2 個參數:
-
$nonce -
$action
隱藏字段中的值 (在示例中為'cabfd9e42d') 表示 $nonce 。
第一個參數是隨機數,來自請求
事實上,wp_verify_nonce()必須像這樣使用:
// here I assume that the form is submitted using 'post' as method
$verify = wp_verify_nonce($_POST['message-send']);
所以傳遞給 wp_verify_nonce()的第一個參數就是隱藏域中存在的值。
第二個參數:wp_create_nonce()方法
關於第二個參數,它取決於你如何構建隨機數值。
例如。如果你這樣做:
<?php $nonce = wp_create_nonce( 'custom-action' ); ?>
<input type="hidden" name="message-send" value="<?php echo $nonce ?>" />
那麼你需要做:
$verify = wp_verify_nonce( $_POST['message-send'], 'custom-action' );
所以,第二個參數是用作 wp_create_nonce()的參數。
第二個參數:wp_nonce_field()方法
如果您使用 wp_nonce_field()創建了隨機數,如:
wp_nonce_field( 'another_action', 'message-send' );
那麼你需要驗證這樣的隨機數:
$verify = wp_verify_nonce( $_POST['message-send'], 'another_action' );
所以,這次,作為 wp_nonce_field()的第一個參數,這個動作就是一切。
Recap
要通過 wp_verify_nonce()驗證,您需要將 2 個參數傳遞給該函數,其中一個是在 nonce 隱藏字段中的值,另一個是該操作,並且取決於如何構建隨機數值。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。