1. 首页
  2. WordPress 函数手册

wp_nonce_field()

wp_nonce_field( int|string $action = -1, string $name = ‘_wpnonce’, bool $referer = true, bool $echo = true )

检索或显示窗体的当前隐藏字段。
Retrieve or display nonce hidden field for forms.

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


说明(Description)

nonce字段用于验证表单内容是否来自当前站点上的位置,而不是其他位置。nonce不能提供绝对的保护,但应该可以防止大多数情况。在表单中使用nonce字段非常重要。$action和$name是可选的,但是如果您想要更好的安全性,强烈建议您设置这两个参数。只调用不带任何参数的函数更容易,因为验证nonce不需要任何参数,但是由于cracker知道默认值是什么,所以他们很难找到绕过nonce的方法并造成损害。输入名称将是您给出的任何$name值。输入值将是nonce创建值。


参数(Parameters)

参数 类型 说明
$action (int | string) 操作名称。
$name (string) 当前名称。
$referer (bool) 是否设置要验证的referer字段。
$echo (bool) 是否显示或返回隐藏表单域。

源码(Source)

/**
 * Retrieve or display nonce hidden field for forms.
 *
 * The nonce field is used to validate that the contents of the form came from
 * the location on the current site and not somewhere else. The nonce does not
 * offer absolute protection, but should protect against most cases. It is very
 * important to use nonce field in forms.
 *
 * The $action and $name are optional, but if you want to have better security,
 * it is strongly suggested to set those two parameters. It is easier to just
 * call the function without any parameters, because validation of the nonce
 * doesn't require any parameters, but since crackers know what the default is
 * it won't be difficult for them to find a way around your nonce and cause
 * damage.
 *
 * The input name will be whatever $name value you gave. The input value will be
 * the nonce creation value.
 *
 * @since 2.0.4
 *
 * @param int|string $action  Optional. Action name. Default -1.
 * @param string     $name    Optional. Nonce name. Default '_wpnonce'.
 * @param bool       $referer Optional. Whether to set the referer field for validation. Default true.
 * @param bool       $echo    Optional. Whether to display or return hidden form field. Default true.
 * @return string Nonce field HTML markup.
 */
function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
	$name = esc_attr( $name );
	$nonce_field = '';

	if ( $referer )
		$nonce_field .= wp_referer_field( false );

	if ( $echo )
		echo $nonce_field;

	return $nonce_field;
}
更新版本 源码位置 使用 被使用
2.0.4 wp-includes/functions.php 4 3

笔记(Notes)

基本示例

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