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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

A Guide to Continuous Integration and Deployment: Learn the fundamentals and understand the use of CI/CD in your apps.

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • Optimize Your Web3 DevOps with User Feedback Forms
  • How To Get and Set PDF Form Fields in Java
  • Three Best React Form Libraries

Trending

  • Architecture Approach: Domain-Driven Design (DDD)
  • The Advantage of Using Cache to Decouple the Frontend Code
  • Architecture Patterns: API Gateway
  • Reading an HTML File, Parsing It and Converting It to a PDF File With the Pdfbox Library
  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.

Jean-Baptiste Jung user avatar by
Jean-Baptiste Jung
·
Apr. 10, 18 · Tutorial
Like (1)
Save
Tweet
Share
7.7K 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

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • Optimize Your Web3 DevOps with User Feedback Forms
  • How To Get and Set PDF Form Fields in Java
  • Three Best React Form Libraries

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • 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: