函数文档

wp_create_nonce()

💡 云策文档标注

概述

wp_create_nonce() 是 WordPress 中用于生成加密令牌的函数,该令牌与特定操作、用户、用户会话和时间窗口绑定,主要用于安全验证以防止 CSRF 攻击。

关键要点

  • 函数返回一个字符串类型的令牌,基于 $action 参数(可选,默认为 -1)、当前用户 ID、会话令牌和时间变量生成。
  • 应在 init 或后续 action hook 中调用,避免在 hook 外使用,否则可能导致问题(参考 ticket #14024)。
  • 内部使用 wp_hash()、wp_nonce_tick() 等函数计算哈希值,并可通过 nonce_user_logged_out 过滤器调整未登录用户的 UID。

代码示例

// 创建 nonce 并用于 URL 链接
$nonce = wp_create_nonce( 'my-nonce' );
echo '<a href="example-page.php?_wpnonce=' . $nonce . '">Perform Action</a>';

// 在目标页面验证 nonce
$nonce = $_REQUEST['_wpnonce'];
if ( ! wp_verify_nonce( $nonce, 'my-nonce' ) ) {
    die( __( 'Security check', 'textdomain' ) );
} else {
    // 执行操作
}

// 更具体的 nonce 命名示例(如删除文章)
wp_create_nonce( 'delete_post-' . $post_id );
wp_verify_nonce( $nonce, "delete_post-{$_REQUEST['post_id']}" );

注意事项

  • nonce 名称应尽可能具体,例如结合操作和对象 ID(如 'delete_post-5'),以增强安全性。
  • 非ce 主要用于短期验证,不应替代其他安全措施如权限检查。

📄 原文内容

Creates a cryptographic token tied to a specific action, user, user session, and window of time.

Parameters

$actionstring|intoptional
Scalar value to add context to the nonce.

Default:-1

Return

string The token.

More Information

The function should be called using the init or any subsequent action hook. Calling it outside of an action hook can lead to problems, see the ticket #14024 for details.

Source

function wp_create_nonce( $action = -1 ) {
	$user = wp_get_current_user();
	$uid  = (int) $user->ID;
	if ( ! $uid ) {
		/** This filter is documented in wp-includes/pluggable.php */
		$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
	}

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

	return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
}

Hooks

apply_filters( ‘nonce_user_logged_out’, int $uid, string|int $action )

Filters whether the user who generated the nonce is logged out.

Changelog

Version Description
4.0.0 Session tokens were integrated with nonce creation.
2.0.3 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example
    In this simple example, we create an nonce and use it as one of the GET query parameters in a URL for a link. When the user clicks the link they are directed to a page where a certain action will be performed (for example, a post might be deleted). On the target page the nonce is verified to insure that the request was valid (this user really clicked the link and really wants to perform this action).

    /*
     * Step A: Create an nonce for a link.
     * We pass it as a GET parameter.
     * The target page will perform some action based on the 'do_something' parameter.
     */
    $nonce = wp_create_nonce( 'my-nonce' );
    ?>
    <a href='myplugin.php?do_something=some_action&_wpnonce=<?php echo esc_attr( $nonce ); ?>'></a>
    
    <pre class="wp-block-code"><code lang="php" class="language-php ">

    /*
    * Step B: This code would go in the target page.
    * We need to verify the nonce.
    */
    $nonce = $_REQUEST[‘_wpnonce’];
    if ( ! wp_verify_nonce( $nonce, ‘my-nonce’ ) ) {
    // This nonce is not valid.
    die( __( ‘Security check’, ‘textdomain’ ) );
    } else {
    // The nonce was valid.
    // Do stuff here.
    }

    In the above example we simply called our nonce my-nonce. It is best to choose a name for the nonce that is specific to the action. For example, if we were to create an nonce that would be part of a request to delete a post, we might call it delete_post. Then to make it more specific, we could append the ID of the particular post that the nonce was for. For example delete_post-5 for the post with ID 5.

    wp_create_nonce( 'delete_post-' . $post_id );

    Then we would verify the nonce like this:

    wp_verify_nonce( $nonce, "delete_post-{$_REQUEST['post_id']}" );

    In general, it is best to make the name for the action as specific as possible.