Home CMS Tutorial WordPress Detailed explanation of Nonce in WordPress

Detailed explanation of Nonce in WordPress

Mar 12, 2021 am 11:40 AM
wordpress

The following tutorial column of WordPress will introduce you to Nonce in WordPress. I hope it will be helpful to friends in need!

Nonce in WordPress

Nonce is the abbreviation of number used once. The nonce of WordPress is not a number, but a string of Hash composed of numbers and characters. The value can not only be used once, but also has a lifetime. During the lifetime, the same parameter will generate the same nonce value for each user until the end of the lifetime. In this article, we will introduce how to use Nonce to prevent CSRF attacks.

Create a Nonce

Nonce can be placed in the Url request or in the Hidden element of a Form, and then used through Javascript during the Ajax request Get him it. The life cycle of a Nonce is only in the current Session. If you log out and then log in again, the previous nonce will also be invalid.

Add nonce to URL

You can add a Nonce to Url through wp_nonce_url() method:

wp_nonce_url( $actionurl, $action, $name );
// 例如:
$complete_url = wp_nonce_url( $bare_url, 'trash-post_'.$post->ID );

where $bare_url (required Select) is the URL to which the nonce is to be added, and $action is the action name defined for the nonce, optional, and the default is -1.

By default, the name of the generated nonce in the link is _wpnonce. In order to avoid possible conflicts, after WordPress 3.6 version, wp_nonce_url added an optional $name parameter, which allows users to specify it themselves. The name of the nonce in the link. For example:

$complete_url = wp_nonce_url( $bare_url, 'trash-post_'.$post->ID, 'my_nonce' );

Add nonce to Form

You can add a hidden element to the form through the wp_nonce_field() method:

PHP

wp_nonce_field( $action, $name, $referer, $echo )
//例如 :
wp_nonce_field( 'delete-comment_'.$comment_id );
wp_nonce_field( $action, $name, $referer, $echo )
//例如 :
wp_nonce_field( 'delete-comment_'.$comment_id );

Call The above method will generate code similar to the following:

<input type="hidden" id="_wpnonce" name="_wpnonce" value="796c7766b1" />
<input type="hidden" name="_wp_http_referer" value="/wp-admin/edit-comments.php" />

Generate a separate nonce

If you just want to generate an independent nonce, you can pass wp_create_nonce() Method:

wp_create_nonce( $action );
// 例如:
$nonce = wp_create_nonce( 'my-action_'.$post->ID );

Similarly, $action is an optional parameter and the default is -1. The above method will return a result similar to "295a686963".

Verify the validity of the nonce

Verify the nonce in the form

In the Admin management interface, you can use the check_admin_referer method to Verify the validity of the Nonce in the Url:

check_admin_referer( $action, $query_arg );

The following is an example demonstrating how to use check_admin_referer to verify the nonce in the plug-in:

<form method="post">
   <!-- some inputs here -->
   <?php wp_nonce_field( &#39;name_of_my_action&#39;, &#39;name_of_nonce_field&#39; ); ?>
</form>

Verification method:

check_admin_referer( 'name_of_my_action', 'name_of_nonce_field' );

Verification Nonce in Ajax

If you want to check the validity of the nonce in the Ajax request, you can use the check_ajax_referer() method:

check_ajax_referer( $action, $query_arg, $die )

$die specifies whether to end script execution if $nonce is invalid . (Default is True)

A simple example of using check_ajax_referer:

<?php
//Set Your Nonce
$ajax_nonce = wp_create_nonce( "my-special-string" );
?>
 
<script type="text/javascript">
jQuery(document).ready(function($){
    var data = {
        action: 'my_action',
        security: '<?php echo $ajax_nonce; ?>',
        my_string: 'Hello World!'
    };
    $.post(ajaxurl, data, function(response) {
        alert("Response: " + response);
    });
});
</script>

Verify backwards through the following code:

add_action( 'wp_ajax_my_action', 'my_action_function' );
function my_action_function() {
    check_ajax_referer( 'my-special-string', 'security' );
    echo sanitize_text_field( $_POST['my_string'] );
    wp_die();
}

Verify the independently generated nonce

1
wp_verify_nonce( $nonce, $action );

The above is the detailed content of Detailed explanation of Nonce in WordPress. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

10 latest tools for web developers 10 latest tools for web developers May 07, 2025 pm 04:48 PM

Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.

How to import the source code of wordpress How to import the source code of wordpress Apr 20, 2025 am 11:24 AM

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

How to add your WordPress site in Yandex Webmaster Tools How to add your WordPress site in Yandex Webmaster Tools May 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to set, get and delete WordPress cookies (like a professional) How to set, get and delete WordPress cookies (like a professional) May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to fix HTTP image upload errors in WordPress (simple) How to fix HTTP image upload errors in WordPress (simple) May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to register a wordpress account How to register a wordpress account Apr 20, 2025 am 11:45 AM

To create an account on WordPress, simply visit its website, select the registration option, fill in the registration form, and verify your email address. Other ways to register include using a Google account or Apple ID. The benefits of signing up include creating a website, gaining features, joining the community, and gaining support.

See all articles