1. 首页
  2. WordPress 函数手册

wp_verify_nonce()

wp_verify_nonce( string $nonce, string|int $action = -1 )

验证是否对时间限制使用了正确的安全一次性事件。
Verifies that a correct security nonce was used with time limit.

目录锚点:#说明#参数#源码#笔记


说明(Description)

nonce在24小时内有效(默认情况下)。


参数(Parameters)

参数 类型 说明
$nonce (string) 用于验证的Nonce值,通常通过表单字段。
$action (string | int) 应该给出正在发生的事情的上下文,并且在创建nonce时是相同的。

源码(Source)

/**
 * Verify that correct nonce was used with time limit.
 *
 * The user is given an amount of time to use the token, so therefore, since the
 * UID and $action remain the same, the independent variable is the time.
 *
 * @since 2.0.3
 *
 * @param string     $nonce  Nonce that was used in the form to verify
 * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
 * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
 *                   0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
 */
function wp_verify_nonce( $nonce, $action = -1 ) {
	$nonce = (string) $nonce;
	$user = wp_get_current_user();
	$uid = (int) $user->ID;
	if ( ! $uid ) {
		/**
		 * Filter whether the user who generated the nonce is logged out.
		 *
		 * @since 3.5.0
		 *
		 * @param int    $uid    ID of the nonce-owning user.
		 * @param string $action The nonce action.
		 */
		$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
	}

	if ( empty( $nonce ) ) {
		return false;
	}

	$token = wp_get_session_token();
	$i = wp_nonce_tick();

	// Nonce generated 0-12 hours ago
	$expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 );
	if ( hash_equals( $expected, $nonce ) ) {
		return 1;
	}

	// Nonce generated 12-24 hours ago
	$expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
	if ( hash_equals( $expected, $nonce ) ) {
		return 2;
	}

	// Invalid nonce
	return false;
}
endif;

if ( !function_exists('wp_create_nonce') ) :
更新版本 源码位置 使用 被使用
2.0.3 wp-includes/pluggable.php 10 2

笔记(Notes)

例子

wp_verify_nonce() 为WP2原创文章,链接:https://www.wp2.cn/functions/wp_verify_nonce/