wp_verify_nonce()获取是否在时间范围内使用了正确的随机数

目录

描述

译文

检查是否在时间范围内使用了正确的随机数。

参数

$nonce

(字符串)(必需)用来验证的随机数

默认值:None

$action

(字符串)(整数)解释当前操作,生成随机数后也应进行同样解释。

默认值:-1

返回的值

无论随机数是否通过验证,都返回布尔变量。

原文

Verify that a nonce is correct and unexpired with the respect to a specified action. The function is used to verify the nonce sent in the current request usually accessed by the $_REQUEST PHP variable.

wp_verify_nonce() 描述

用法

<?php wp_verify_nonce$nonce$action ); ?>

wp_verify_nonce() 用法

参数

$nonce

(string) (必填) Nonce to verify.

默认值: None

$action

(string/int) (可选) Action name. Should give the context to what is taking place and be the same when the nonce was created.

默认值: -1

wp_verify_nonce() 参数

返回值

(boolean/integer

Boolean false if the nonce is invalid. Otherwise, returns an integer with the value of:

  • 1 – if the nonce has been generated in the past 12 hours or less.
  • 2 – if the nonce was generated between 12 and 24 hours ago.

wp_verify_nonce() 返回值

历史

添加于 版本: 2.0.3

wp_verify_nonce() 历史

源文件

wp_verify_nonce() is defined in wp-includes/pluggable.php

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * 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') ) :

wp_verify_nonce() 源文件

相关