search
HomeCMS TutorialWordPressDetailed explanation of Nonce in 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>
<input>

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:


       

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>
jQuery(document).ready(function($){
    var data = {
        action: &#39;my_action&#39;,
        security: &#39;<?php echo $ajax_nonce; ?>&#39;,
        my_string: &#39;Hello World!&#39;
    };
    $.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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

How customizable is WordPress, really?How customizable is WordPress, really?May 11, 2025 am 12:11 AM

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.

What are the core features of WordPress as a CMS?What are the core features of WordPress as a CMS?May 10, 2025 am 12:15 AM

WordPressisanexcellentchoiceforaCMSduetoitsuser-friendlyinterface,extensiveecosystem,SEOcapabilities,scalability,andsupportivecommunity.1)Itsintuitivedashboardmakescontentmanagementeasyforallusers.2)Thevastarrayofthemesandpluginsallowsforextensivecus

How easy is it to manage content with WordPress?How easy is it to manage content with WordPress?May 09, 2025 am 12:11 AM

WordPressisuser-friendlyduetoitsintuitiveinterfaceandCMS,whichseparatescontentfromdesign.Itoffersarichtexteditorforeasycontentcreationandamedialibraryfororganization.Itsflexibilityisenhancedbynumerousthemesandplugins,thoughoverusecanimpactperformance

How is WordPress used in business settings?How is WordPress used in business settings?May 08, 2025 am 12:04 AM

WordPressissuitableforbusinesssettings.1)Itsupportse-commercewithpluginslikeWooCommerce,allowingproductmanagementandpaymentprocessing.2)ItservesasaCMSforcorporateblogs,enhancingSEOandengagement.3)Customizationispossiblewithnumerousthemesandplugins.4)

What types of websites are not a good fit for WordPress?What types of websites are not a good fit for WordPress?May 07, 2025 am 12:10 AM

WordPressisnotidealforhigh-trafficwebsites,customandcomplexapplications,security-sensitiveapplications,real-timedataprocessing,andhighlycustomizeduserinterfaces.Forhigh-trafficsites,useNext.jsorcustomsolutions;forcomplexapplications,optforDjangoorRub

Can you build a blog with WordPress?Can you build a blog with WordPress?May 06, 2025 am 12:03 AM

Yes,youcanbuildablogwithWordPress.1)ChoosebetweenWordPress.comforbeginnersorWordPress.orgformorecontrol.2)Selectathemetopersonalizeyourblog'slook.3)Usepluginstoenhancefunctionality,likeSEOandsocialmediaintegration.4)Customizeyourthemewithsimplecodetw

How secure is WordPress as a CMS platform?How secure is WordPress as a CMS platform?May 05, 2025 am 12:01 AM

WordPresscanbesecureifmanagedproperly.1)KeeptheWordPresscoreupdatedtopatchvulnerabilities.2)Vetandupdatepluginsandthemesfromreputablesources.3)Enforcestrongpasswordsandusetwo-factorauthentication.4)Chooseahostingproviderwithgoodsecuritypractices.5)Ed

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft