問題描述

我可以看到 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 個引數:

  1. $nonce

  2. $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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。