DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Dynamic Web Forms In React For Enterprise Platforms
  • How to Get Word Document Form Values Using Java
  • Lightning Data Service for Lightning Web Components
  • Dynamic Forms With Camunda and Spring StateMachine

Trending

  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Top Book Picks for Site Reliability Engineers
  • A Complete Guide to Modern AI Developer Tools
  • Automatic Code Transformation With OpenRewrite
  1. DZone
  2. Coding
  3. Frameworks
  4. Securing WordPress AJAX Forms Using Nonces

Securing WordPress AJAX Forms Using Nonces

In this article, we will take a look at how you as a developer can use nonces to protect AJAX requests on a WordPress site.

By 
Jean-Baptiste Jung user avatar
Jean-Baptiste Jung
·
Apr. 10, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

When creating a WordPress theme or plugin, AJAX is often used in order to enhance the user experience. In order to ensure security and protect your site against several types of attacks including CSRF, WordPress provides security tokens called nonces. In this article, I'll show you how to use nonces to protect AJAX requests on a WordPress site.

What Are WordPress Nonces?

According to the codex, a nonce is a "number used once" to help protect URLs and forms from certain types of misuse, malicious or otherwise.

WordPress can create nonces for them to be submitted via form or another action, and on the other hand, it can verify the nonce passed in a form or an action is valid before accepting the associated data.

For more info about nonces, check out the WordPress codex.

The Form

For this tutorial, we need to create two files: ajax.php, which will contain the code needed to process the request, and page-form.php, the main file, containing a simple form. Using a nonce adds an extra layer of security to WordPress themes and plugin you might create.

Those two files should be created in your WordPress theme directory. You can either use an FTP program or the cPanel provided by your web hosting to do so.

Let's start by creating a simple HTML form in the page-form.php file.

<form id="myform">
  <div class="form-group">
    <label for="formGroupExampleInput">Example label</label>
    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
  </div>
  <div class="form-group">
    <label for="formGroupExampleInput2">Another label</label>
    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
  </div>

  <?php wp_nonce_field( 'my_nonce' ); ?>

  <input type="submit" id="submit" value="Submit" />

</form>

Nothing special about this form, except a call to wp_nonce_field() on line 11. This function creates a nonce and adds it to the form using a hidden field. Another hidden field is created by the same function to store the referer.

If you look at the source of your page-form.php file, you'll see that the wp_nonce_field() function has outputted something similar to the following:

<input type="hidden" id="_wpnonce" name="_wpnonce" value="ad8a767ba0" />
<input type="hidden" name="_wp_http_referer" value="/myaccount/mypage/" />

For more information on the function, don't hesitate to refer to the codex.

Sending the Form Using jQuery

Now, we're going to use some jQuery to send our form.

jQuery( document ).ready(function() {
jQuery( "#submit" ).click(function() {
 jQuery.post( "https://yoursite.com/ajax.php", jQuery('#myform').serialize())
.done(function( data ) {
alert(data);
}); 
return false;
});
});

The code is pretty self-explanatory: when the user attempts to send the form, jQuery sends an AJAX request to https://yoursite.com/ajax.php, with the serialized form as content.

Verifying the Nonce Using PHP

Once the data has been sent, we need to verify that the nonce is valid. Here's the content of the ajax.php file to which jQuery has sent the data:

<?php
define( 'WP_USE_THEMES', false );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

if (!check_ajax_referer( 'my_nonce' )){
wp_die();
}

// If the nonce is correct, process the data

Lines 2 and 3 are including WordPress in the file. This step is necessary since we need the WordPress core to be included in order to use WP functions.

On line 5, WordPress is checking for a nonce named my_nonce using the check_ajax_referer() function, which returns true if the nonce is valid.

If the nonce is not valid, wp_die() is called and the execution of the script will be terminated. Otherwise, the script will proceed your data as needed.

AJAX Form (document) WordPress

Published at DZone with permission of Jean-Baptiste Jung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Dynamic Web Forms In React For Enterprise Platforms
  • How to Get Word Document Form Values Using Java
  • Lightning Data Service for Lightning Web Components
  • Dynamic Forms With Camunda and Spring StateMachine

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: