check_ajax_referer()
最后更新于:2021-11-25 20:28:41
check_ajax_referer( int|string$action=-1, false|string$query_arg=false, bool$die=true)Verifies the Ajax request to prevent processing requests external of the blog.
参数
- $action
-
(int|string) (Optional) Action nonce.
Default value: -1
- $query_arg
-
(false|string) (Optional) Key to check for the nonce in
$_REQUEST
(since 2.5). If false,$_REQUEST
values will be evaluated for ‘_ajax_nonce’, and ‘_gcnonce’ (in that order).Default value: false
- $die
-
(bool) (Optional) Whether to die early when the nonce cannot be verified.
Default value: true
响应
(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.
源文件
文件: gc-includes/pluggable.php
function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
if ( -1 == $action ) {
_doing_it_wrong( __FUNCTION__, __( 'You should specify an action to be verified by using the first parameter.' ), '4.7.0' );
}
$nonce = '';
if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) ) {
$nonce = $_REQUEST[ $query_arg ];
} elseif ( isset( $_REQUEST['_ajax_nonce'] ) ) {
$nonce = $_REQUEST['_ajax_nonce'];
} elseif ( isset( $_REQUEST['_gcnonce'] ) ) {
$nonce = $_REQUEST['_gcnonce'];
}
$result = gc_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 ( gc_doing_ajax() ) {
gc_die( -1, 403 );
} else {
die( '-1' );
}
}
return $result;
}
<?php //Set Your Nonce $ajax_nonce = gc_create_nonce( "gcdocs-special-string" ); ?> <script type="text/javascript"> jQuery(document).ready(function($){ var data = { action: 'gcdocs_action', security: '<?php echo $ajax_nonce; ?>', gcdocs_string: 'Hello World!' }; $.post(ajaxurl, data, function(response) { alert("Response: " + response); }); }); </script>