wp_verify_nonce

函数
wp_verify_nonce ( $nonce, $action = -1 )
参数
  • (string) $nonce Nonce value that was used for verification, usually via a form field.
    Required:
  • (string|int) $action Should give context to what is taking place and be the same when nonce was created.
    Required:
    Default: -1
返回值
  • (int|false) 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. False if the nonce is invalid.
定义位置
相关方法
wp_version_checkwp_explain_noncewp_create_noncewp_recovery_modewp_tiny_mce
引入
2.0.3
弃用
-

wp_verify_nonce: 这个函数用来验证一个给定的nonce是否有效。它需要两个参数:nonce字符串和与nonce相关的行动名称。如果nonce是有效的,该函数返回true,否则返回false。

验证是否使用了正确的安全nonce,并有时间限制。

一个nonce的有效期为24小时(默认)。

function wp_verify_nonce( $nonce, $action = -1 ) {
		$nonce = (string) $nonce;
		$user  = wp_get_current_user();
		$uid   = (int) $user->ID;
		if ( ! $uid ) {
			/**
			 * Filters 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|int $action The nonce action, or -1 if none was provided.
			 */
			$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
		}

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

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

		// 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;
		}

		/**
		 * Fires when nonce verification fails.
		 *
		 * @since 4.4.0
		 *
		 * @param string     $nonce  The invalid nonce.
		 * @param string|int $action The nonce action.
		 * @param WP_User    $user   The current user object.
		 * @param string     $token  The user's session token.
		 */
		do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token );

		// Invalid nonce.
		return false;
	}
endif;

if ( ! function_exists( 'wp_create_nonce' ) ) :
	/**
	 * Creates a cryptographic token tied to a specific action, user, user session,
	 * and window of time.
	 *
	 * @since 2.0.3
	 * @since 4.0.0 Session tokens were integrated with nonce creation.
	 *
	 * @param string|int $action Scalar value to add context to the nonce.
	 * @return string The token.
	 */

常见问题

FAQs
查看更多 >