函数文档

check_admin_referer()

💡 云策文档标注

概述

check_admin_referer() 函数用于验证用户是否从另一个管理页面通过正确的安全 nonce 被引用,以确保操作意图,防止点击劫持攻击。它不检查用户权限,需结合 current_user_can() 使用。

关键要点

  • 验证用户意图而非授权,需配合 current_user_can() 进行权限检查
  • 参数 $action 为 nonce 动作,$query_arg 指定 $_REQUEST 中 nonce 的键,默认 '_wpnonce'
  • 返回值:1 表示 nonce 有效且在 0-12 小时内生成,2 表示在 12-24 小时内生成,false 表示无效
  • 从 WordPress 3.2 起,不指定 $action 参数会触发 _doing_it_wrong() 警告(若 WP_DEBUG 为 true 则终止)
  • 从 2.0.1 起,仅当 $action 未指定(或为默认 -1)时才检查 referer,以向后兼容无 nonce 的情况
  • 如果 nonce 无效或未发送,函数会调用 wp_nonce_ays() 并终止执行

代码示例

// 在插件选项页面使用示例
// 表单中添加 nonce 字段
wp_nonce_field('my_action', 'my_nonce_field');

// 提交处理页面验证
if (isset($_POST['submit'])) {
    check_admin_referer('my_action', 'my_nonce_field');
    // 验证通过后执行操作
}

注意事项

  • 使用时不指定 $action 参数已过时,建议始终提供明确的 nonce 动作
  • 函数主要用于保护管理页面操作,确保请求来源可靠
  • 相关函数包括 wp_verify_nonce()、wp_nonce_ays() 和 wp_get_referer()

📄 原文内容

Ensures intent by verifying that a user was referred from another admin page with the correct security nonce.

Description

This function ensures the user intends to perform a given action, which helps protect against clickjacking style attacks. It verifies intent, not authorization, therefore it does not verify the user’s capabilities. This should be performed with current_user_can() or similar.

If the nonce value is invalid, the function will exit with an “Are You Sure?” style message.

Parameters

$actionint|stringoptional
The nonce action.

Default:-1

$query_argstringoptional
Key to check for nonce in $_REQUEST. Default '_wpnonce'.

Return

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.

More Information

  • Using the function without the $action argument is obsolete and, as of Version 3.2, if WP_DEBUG is set to true, the function will die with an appropriate message (“You should specify a nonce action to be verified by using the first parameter.” is the default).
  • As of 2.0.1, the referer is checked only if the $action argument is not specified (or set to the default -1) as a backward compatibility fallback for not using a nonce. A nonce is prefered to unreliable referers and with $action specified the function behaves the same way as wp_verify_nonce() except that it dies after calling wp_nonce_ays() if the nonce is not valid or was not sent.

Source

function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
	if ( -1 === $action ) {
		_doing_it_wrong( __FUNCTION__, __( 'You should specify an action to be verified by using the first parameter.' ), '3.2.0' );
	}

	$adminurl = strtolower( admin_url() );
	$referer  = strtolower( wp_get_referer() );
	$result   = isset( $_REQUEST[ $query_arg ] ) ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action ) : false;

	/**
	 * Fires once the admin request has been validated or not.
	 *
	 * @since 1.5.1
	 *
	 * @param string    $action The nonce action.
	 * @param false|int $result 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.
	 */
	do_action( 'check_admin_referer', $action, $result );

	if ( ! $result && ! ( -1 === $action && str_starts_with( $referer, $adminurl ) ) ) {
		wp_nonce_ays( $action );
		die();
	}

	return $result;
}

Hooks

do_action( ‘check_admin_referer’, string $action, false|int $result )

Fires once the admin request has been validated or not.

Changelog

Version Description
2.5.0 The $query_arg parameter was added.
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Usage in a plugin’s option page

    Here is an example of how you might use this in a plugin’s option page. You add a nonce to a form using the wp_nonce_field() function:

    <form method="post">
       <!-- some inputs here ... -->
       
    </form>

    Then in the page where the form submits to, you can verify whether or not the form was submitted and update values if it was successfully submitted:

    </pre>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-1105' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fcheck_admin_referer%2F%3Freplytocom%3D1105%23feedback-editor-1105" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-1106" data-comment-id="1106" class="comment byuser comment-author-codex odd alt thread-odd thread-alt depth-1">
    			<article id="div-comment-1106" class="comment-body">
    
    							<a href="#comment-content-1106" class="screen-reader-text">Skip to note 4 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/codex/" rel="external nofollow" class="url">Codex</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/functions/check_admin_referer/#comment-1106">
    							<time datetime="2016-02-12T11:41:12+00:00">
    							10 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="d11c9100ee" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="1106" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fcheck_admin_referer%2F%23comment-1106"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title="100% like this"><span class="screen-reader-text">Vote results for this note: </span>1</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="1106" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fcheck_admin_referer%2F%23comment-1106"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-1106">
    				<p><strong>Note – Obsolete usage</strong></p>
    <p>script dies if the admin referer is not validated.</p>
    <pre class="wp-block-code"><code lang="php" class="language-php ">