wordpress wp_create_nonce随机数函数
wordpress的wp_create_nonce随机数函数可以增强程序的安全性,防止恶意提交数据,常用于get,post判断随机数是否一致确定程序安全。下面我看看wp_create_nonce函数的用法:
<?php
// 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 $nonce; ?>'>Do some action</a>
<?php
// 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' );
} else {
// The nonce was valid.
// Do stuff here.
}
?>
以上代码示例演示了通过比较$_GET得到的随机数,和预先设定的随机数是否一致,判断操作是否合法。
wp_create_nonce函数用于产生随机数,参数自定或者用一个变量,比如
wp_create_nonce( 'delete_post-' . $post_id ); wp_create_nonce( 'my' . $post_id ); wp_create_nonce( 'nihao' );
验证随机数是否一致的函数可用wp_verify_nonce函数,用法:
wp_verify_nonce( $nonce, 'delete_post-' . $_REQUEST['post_id'] );
第一个参数$nonce用于接受到的通过url传递过来的随机数,第二个参数就是创建随机数时的字符串,可以是自定的,也可以是变量,但要保证一致。
