验证Ajax请求以防止处理博客外部的请求。
原型
check_ajax_referer( int|string $action = -1, false|string $query_arg = false, bool $die = true )
参数
$action
(int|string)
(Optional)
行动现时。
$query_arg
(false|string)
(Optional)
在$ _REQUEST中检查nonce的关键(自2.5起)。如果为false,将为’_ajax_nonce’和’_wpnonce’(按此顺序)计算$ _REQUEST值。
$die
(bool)
(Optional)
当nonce无法验证时是否早死。
返回值
(false|int)
如果nonce无效,则为false;如果nonce有效并且在0-12小时之前生成,则为1;如果nonce有效并且在12-24小时之前生成,则为2。
源文件
路径:wp-includes/pluggable.php
<?php
...
function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
if ( -1 == $action ) {
_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '4.7' );
}
$nonce = '';
if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
$nonce = $_REQUEST[ $query_arg ];
elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
$nonce = $_REQUEST['_ajax_nonce'];
elseif ( isset( $_REQUEST['_wpnonce'] ) )
$nonce = $_REQUEST['_wpnonce'];
$result = wp_verify_nonce( $nonce, $action );
/**
* Fires once the Ajax request has been validated or not.
*
* @since 2.1.0
*
* @param string $action The Ajax 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_ajax_referer', $action, $result );
if ( $die && false === $result ) {
if ( wp_doing_ajax() ) {
wp_die( -1, 403 );
} else {
die( '-1' );
}
}
return $result;
}
...
?>
其他
英文文档:https://developer.wordpress.org/reference/functions/check_ajax_referer/