🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
为了安全起见,生成用于验证请求的起源和意图的生成数字。 每个随机数只能使用一次。 如果您的插件允许用户提交数据; 无论是在行政部门还是公共方面; 您必须确保用户是他们所说的,他们具有执行操作的必要功能。 同时进行这两项意味着数据只会在用户期望更改时发生变化。 ##使用Nonces 按照我们检查用户功能的示例,用户数据提交安全性的下一步是使用随机数。 功能检查确保只有具有删除帖子权限的用户才能删除帖子。但是如果有人欺骗你点击那个链接呢?你有必要的能力,所以你可以不经意地删除一个职位。 可以使用Nonces来检查当前用户是否实际打算执行该操作。 当您生成删除链接时,您将需要使用wp_create_nonce()函数将一个随机数添加到链接中,传递给该函数的参数可确保正在创建的随机数对该特定操作是唯一的。 然后,当您处理删除链接的请求时,可以检查该随机数是您期望的内容。 有关更多信息,马克·贾奇斯(James Jaquith)在WordPress中的发布是一个很好的资源。 ##完整例子 使用功能检查,数据验证,安全输入,安全输出和随机数的完整示例: ``` <?php /** * generate a Delete link based on the homepage url */ function wporg_generate_delete_link($content) { // run only for single post page if (is_single() && in_the_loop() && is_main_query()) { // add query arguments: action, post, nonce $url = add_query_arg( [ 'action' => 'wporg_frontend_delete', 'post' => get_the_ID(), 'nonce' => wp_create_nonce('wporg_frontend_delete'), ], home_url() ); return $content . ' <a href="' . esc_url($url) . '">' . esc_html__('Delete Post', 'wporg') . '</a>'; } return null; } /** * request handler */ function wporg_delete_post() { if ( isset($_GET['action']) && isset($_GET['nonce']) && $_GET['action'] === 'wporg_frontend_delete' && wp_verify_nonce($_GET['nonce'], 'wporg_frontend_delete') ) { // verify we have a post id $post_id = (isset($_GET['post'])) ? ($_GET['post']) : (null); // verify there is a post with such a number $post = get_post((int)$post_id); if (empty($post)) { return; } // delete the post wp_trash_post($post_id); // redirect to admin page $redirect = admin_url('edit.php'); wp_safe_redirect($redirect); // we are done die; } } if (current_user_can('edit_others_posts')) { /** * add the delete link to the end of the post content */ add_filter('the_content', 'wporg_generate_delete_link'); /** * register our request handler with the init hook */ add_action('init', 'wporg_delete_post'); } ```