WordPress nonce, What is WordPress nonce and how it works

What is WordPress nonce and how it works?

Today, I am going to share with you a tip that how we can make our WordPress plugins are themes more secure. I have seen in my plugins and themes where WordPress developers are not using WordPress nonces even though it is VERY important. If you are working as a WordPress freelancer developer and g custom plugins or themes, I am sure this article is going to be very helpful for you.

What actually WordPress nonce means?

WordPress Nonce basically in short is the term used for number used once. It’s a string value, a temporary unique key that is generated by WordPress automatically and acts as a special security token to check whether you are the same person who’s performing an action or someone else while submitting a form, adding a post, deleting a post, etc.

Why we should use WordPress nonce?

The main purpose of the nonce is to protect your site from malicious hacking attacks such as Cross-Site Request Forgery (CSRF) or sometimes pronounced sea-surf or XSRF, which is used to trick someone to submit a form or click on a link that will cause harm to your site.

How nonce works in WordPress?

It is very simple. As I mentioned earlier that it is generated by WordPress itself and when a form is submitted or a link is clicked, WordPress checks the nonce value and if it matches, you are free to proceed.

A thing to remember, you don’t need to do anything about nonce in those forms or links which are generated by WordPress, like “add post”, “edit post”, but you have to use nonce in your custom build plugins or themes you will create later.

How to use nonce in WordPress?

Before we walk you through a complete example of how to implement a nonce in a form or in a URL, lets us understand how the nonce works in WordPress.

There are three steps that we must follow to implement a nonce in WordPress plugin or a theme:

1. How to create a nonce.
2. How to pass a nonce through a Form or URL.
3. How to verify a nonce before doing a specific action.

1. How to create a nonce?

To create a nonce, there is a function name “wp_create_nonce ($action)”, which generates and returns a unique value based on the current time and the $action.
The “$action” parameter is optional but recommended, $action parameter refers to what will happen.

$nonce= wp_create_nonce('delete-post');

2. How to pass a nonce through a Form or URL?

How to pass a nonce in URLs.

<a href="myplugin.php?_wpnonce=<?php echo $nonce; ?>">

How to pass a nonce in Forms.

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

We use “wp_nonce_field($action,$name)” to pass a nonce through forms. wp_nonce_field() function will generate a hidden input field which stores a nonce value and can be retrieved later on.

The parameter “name_of_my_action” is the context in which you are using the nonce field and “name_of_nonce_field” is any name you want to specify. Default is “_wpnonce”. It’s better to use $action and $name parameter for better security.

3. How to verify a nonce?

After putting it into the form you can get it like this:

if ( isset( $_POST['name_of_nonce_field'] ) &&
wp_verify_nonce( $_POST[‘name_of_nonce_field’], ‘name_of_my_action’ ) ) {

// process form data

} else {
print ‘Sorry, your nonce did not verify. It is a secure WordPress site. go get a coffee !!';
exit;
}

Example:

In this example, we are creating a form and an embedded nonce field in it. This form can be used for your contact page or anything you like for your site where you are taking inputs from users.

The HTML code for the form is (notice the wp_nonce_field function):

<form id="form">
<?php wp_nonce_field( 'contact_form_submit', 'cform_generate_nonce' );?>
            <label>Name</label> <input type="text" name="name" class="text" id="name"><br>
            <label>Email</label> <input type="email" name="email" class="text" id="email"><br>

            <label>Subject</label> <input type="text" name="subject" class="text" id="subject"><br>
            <label>Message</label><textarea id="message" class="textarea" name="message"></textarea>
            <input name="action" type="hidden" value="simple_contact_form_process" />
            <input type="submit" name="submit_form" class="button" value="send Message" id="sendmessage">
            <div class="formmessage"><p></p></div>
        </form>

So, you have your contact form ready and now want to take the data from form inputs and process it. Form Inputs are the doors where mostly malicious attacks happen and hackers run anything they like. So, you should properly sanitize your inputs which are very important for your website security.

Here is how you will verify nonce in your contact form.

<?php

if(isset($_POST['submit_form'])) {
  if(!wp_verify_nonce('cform_generate_nonce','contact_form_submit')){
      wp_die('Our Site is protected!!');
   }else{
      // process here your contact form with proper sanitize inputs.
  }
}

?>

Conclusion

WordPress nonce is playing a very important role in WordPress security and I recommend it should be implemented in every WordPress plugin and theme, but I see many plugins and themes are not using it. If this article was helpful for you in any way I would love to hear your feedback.

How to make WordPress database secure by changing default WordPress table prefix?

How to make WordPress database secure by changing default WordPress table prefix?

WordPress Database Security is the most important thing. Every single piece of information stored in it, which makes hackers and bots to target for stealing information by applying SQL Injection.

WordPress Database uses a default table prefix value “wp_” for all of its database tables. Typically, every website that is running WordPress will have its database tables with this prefix and this can surely be used by the hackers or malicious bots to guess your database table names. That’s why the smartest thing to do while creating a WordPress website is to change the prefix of the database, which can be done easily.

If you forgot to change the prefix of the database table while creating your WordPress website, you can do this now by following these simple steps.

Note: It’s recommended to backup your database before performing this task.

There are two simple steps you need to follow:

Step 1. By changing the wp-config.php file:

  • Go to your WordPress root directory and search for a file named “wp-config.php”.
wp-config.php file
wp-config.php
  1. Open “wp-config.php” in any code editor and search for “$table_prefix  = ‘wp_’;”
  2. Change “wp_” prefix to something like “Br1G@de” or anything you like.
WordPress database table prefix
Table Prefix
Note: Only alphabets, numbers and underscores.

Step 2. Change database table names:

Now you need to access your database using phpMyAdmin and change the table name’s prefix with the new one we entered in “wp-config.php” file.

You will find the phpMyAdmin link in cPanel under Databases section.

phpMyAdmin Database
phpMyAdmin

By default there are normally total 11 tables listed

WordPress Database Default Tables
Default Tables

Select the SQL tab and run the simple queries and use the prefix you add in “wp-config.php” file.

RENAME table `wp_commentmeta` TO `Br1G@de_commentmeta`;
RENAME table `wp_comments` TO `Br1G@de_comments`;
RENAME table `wp_links` TO `Br1G@de_links`;
RENAME table `wp_options` TO `Br1G@de_options`;
RENAME table `wp_postmeta` TO `Br1G@de_postmeta`;
RENAME table `wp_posts` TO `Br1G@de_posts`;
RENAME table `wp_terms` TO `Br1G@de_terms`;
RENAME table `wp_term_relationships` TO `Br1G@de_term_relationships`;
RENAME table `wp_term_taxonomy` TO `Br1G@de_term_taxonomy`;
RENAME table `wp_usermeta` TO `Br1G@de_usermeta`;
RENAME table `wp_users` TO `Br1G@de_users`;
 Note: If you have plugins installed, you have to make changes to those tables as well same we just did it with default WordPress tables.
WordPress, WordPress development

How To Create Custom Post Types In WordPress Admin?

Now a days, WordPress is not just a blogging platform. From past few years, WordPress has become a robust content management system. By default, WordPress has two main post types:

  • Post
  • Pages

but you can create your own custom content types you want, these custom content types are referred as custom post types.  So when the WordPress is giving you the option to go beyond blogging platform and line up your content management system so there is no reason not to create custom post type WordPress. So today we will show you how you can easily create your own custom post types.

What is custom post type?

WordPress has many post types like:

  • post
  • page
  • attachment
  • revision
  • menu

by default. But, sometimes you might be requiring some custom post types according to your requirements. For example, You may need to create a custom post type for products for an e-commerce website, for assignments for an e-learning website, or for movies for a review website.

How to create custom post types?

To create a custom post type, you can either create a new custom post type plugin or if you are working with themes you can paste the following code in Active theme of “functions.php” file.

add_action( 'init', 'custom_post_type' );

function custom_post_type() {
    register_post_type( 'php_book',
        array(
            'labels' => array(
                'name' => __( 'Books' ),
                'singular_name' => __( 'Book' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'books'),

        )
    );
}

First, we will walk you through with a fully working example of custom post type plugin so you understand how it works, take a look at below code. Create a new file in /wp-content/plugins/custom_post_types_plugin.php and paste the following code in it.

<?php

/*
Plugin Name: Custom Post Types Plugin By WPBrigade
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: Example to create your own custom post types plugin.
Version: 1.0
Author: WPBrigade
Author URI: http://www.twitter.com/WPBrigade
License: A "Slug" license name e.g. GPL2
*/

add_action( 'init', 'custom_post_type' );

function custom_post_type() {
    register_post_type( 'php_book',
        array(
            'labels' => array(
                'name' => __( 'Books' ),
                'singular_name' => __( 'Book' )
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'books'),

        )
    );
}

 

To create a new post type, we will use the register_post_type() function.

In “custom_post_type()” function we registers a post type with name of “php_book” with an array of arguments. These arguments are the options for our custom post type and has two parts, first array has label name of our custom post type and singular name for custom post. Second array include other arguments like public visibility, archive  and slug that will be used in URLs for this post type. You can learn more about using slug in WordPress here.

And what if you have no mood to do the coding thing, so there is always a option to go for custom post type plugin . For this  we need to activate our WordPress custom post type plugin from “Plugins” area.

Activate Plugin

 

After activating the Custom Post Type Plugin from plugins page you will see the new Custom Post Type with the name “Books” in admin area.

wordpress admin panel
wordpress admin panel

 

To add a new post you need to go to Book post from admin panel and click Add New.

Add New Book
Add New Book

You can see the entries of book types like this.

Books - Custom Post Types
Books – Custom Post Types

Of course, you want to see the added books in front end of your site. If you will see the page in front end you will be having a 404 error, probably.

404 Page Not Found - Custom Post Types
404 Page Not Found – Custom Post Types

Why? Because, you have to rearrange the rewrite rules as you have added new route/slug for book type entries.

Go to your permalink settings, change them to default and then again to your desired URL structure. Now if you will open the page to view the added book, you will surely be seeing the correct page.

Archive Page - Custom Post Types
Archive Page – Custom Post Types

 

See the list of all of the arguments that can be passed to register_post_type.

interact with WordPress APis, how to add a custom field via wordpress

How To Interact With An API Using WordPress Standard Functions?

To interact with APIs is a very common thing in Web Development, WordPress gives us the utility functions to interact with APIs. As you know to interact with an API requires good knowledge of cURL and many other things, WordPress takes this responsibility and wrap the inner stories into utility functions for you.

wp_remote_get is the function that gets the data for you from an API. All you have to do is just put the endpoint as an argument and voila! It’s magic.

This function basically takes two arguments
1. $url – Resource to retrieve data from. This must be in a standard HTTP format
2. $args – OPTIONAL – You may pass an array of arguments in here to alter behavior and headers, such as cookies, follow redirects, etc.

Let’s make a call to GitHub API and see what happens.

$response = wp_remote_get( 'https://api.github.com/users/ifiwfi' );

It will retrieve the following data:

Array
(
[headers] => Array
(
[server] => GitHub.com
[date] => Thu, 12 Mar 2015 13:46:33 GMT
[content-type] => application/json; charset=utf-8
[connection] => close
[status] => 200 OK
[x-ratelimit-limit] => 60
[x-ratelimit-remaining] => 58
[x-ratelimit-reset] => 1426171579
[cache-control] => public, max-age=60, s-maxage=60
[last-modified] => Wed, 04 Mar 2015 18:42:08 GMT
[etag] => W/"87972c50f954668862db38480dab5c78"
[vary] => Array
(
[0] => Accept
[1] => Accept-Encoding
)

[x-github-media-type] => github.v3
[x-xss-protection] => 1; mode=block
[x-frame-options] => deny
[content-security-policy] => default-src 'none'
[access-control-allow-credentials] => true
[access-control-expose-headers] => ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
[access-control-allow-origin] => *
[x-github-request-id] => 6E271E7B:376A:68977C5:550198B8
[strict-transport-security] => max-age=31536000; includeSubdomains; preload
[x-content-type-options] => nosniff
[x-served-by] => 07ff1c8a09e44b62e277fae50a1b1dc4
[content-encoding] => gzip
)

[body] => {"login":"ifiwfi","id":6972531,"avatar_url":"https://avatars.githubusercontent.com/u/6972531?v=3","gravatar_id":"","url":"https://api.github.com/users/ifiwfi","html_url":"https://github.com/ifiwfi","followers_url":"https://api.github.com/users/ifiwfi/followers"}
[response] => Array
(
[code] => 200
[message] => OK
)

[cookies] => Array
(
)

[filename] => 
)

If you want to get the body part from the response, you can do like this:

$response = wp_remote_get( 'https://api.github.com/users/ifiwfi' );
$body = wp_remote_retrieve_body( $response );

If you want to get the response code, you can do like this:

$response = wp_remote_get( 'https://api.github.com/users/ifiwfi' );
$http_code = wp_remote_retrieve_response_code( $response );

The next part of the interaction is to post the values to an API. You can use this function wp_remote_post. This function takes the first argument the URL on which the data has to be posted and the second argument the data which has to be posted. The data should be in the key value pair array. As GitHub doesn’t let us post data so we just assume some URLs.

$body = array(
'name' => 'Irfan Ahmed',
'profession' => 'Software engineer',
'email' => '[email protected]',
'subject' => 'How to post data to a form or API',
'comment' => 'Hey, I learned a lot from this article.'
);

$args = array(
'body' => $body,
'timeout' => '10',
'redirection' => '3',
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'cookies' => array()
);

$response = wp_remote_post( 'http://yourwebsite.com/contact/', $args );

The last important thing is to make any kind of call. Like you want to delete an object from database table using the API. It will be done like this:

$args = array(
'method' => 'DELETE'
);
$response = wp_remote_request( 'http://api.yourwebsite.com/object/to/delete', $args );

This is the most easiest and interactive way to use an API using WordPress using standard functions. Feel free to comment below and let us know how this tutorial helps you.

how to setup HTTPS in wordpress site

What is HTTPS and How to Setup HTTPS in WordPress Site?

One of the most important features which you should have to ensure that your WordPress website is secure and safe for those users who want to exchange their important information on your website while shopping or doing other stuff. Setting up your WordPress website to force use the most secure transaction system is not that difficult to implement, but it needs a lot of decision making when to enforce a secure transaction process for the user.

You would have seen on some websites, their URLs starting with “HTTPS” like Facebook, Google, and many others. An “HTTPS” enabled websites to add a security layer to the data communication between your computer and the server. The data communication is encrypted with an SSL (Secure Sockets Layer) certificate.

The next question in your mind will surely be “Why do you need it?”.

Any sensitive information like your credit card details, your passwords, or anything which could be called sensitive, needs to be safe whenever it is sent towards the server so that nobody between you and the server you are interacting with can get it. That’s why most of the shopping sites don’t use “HTTP”. The next important question is how you can enable SSL on your WordPress site. It is very easy.

Setting up your WordPress site with HTTPS:

First, you have to purchase an SSL certificate for your site and install it on your domain. Then go to the WordPress admin and open the settings page. There you will see these two text fields.

wordpressURL fields

Just change your URLs by putting adding “s” after “HTTP” and save it. The next step is to open your “.htaccess” file which is residing in the root of your WordPress and put this code into that file.

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*)  https://%{SERVER_NAME}/$1 [R,L]

Let me explain the above code.

First-line will check whether the URL which has been entered by the user is having “HTTPS” or not and will be true if it is not having “HTTPS”.

In this part “https://%{SERVER_NAME}/$”

{SERVER_NAME} = “domain name”
^/?(.*) = “the slash is representing that slash, which is coming after the domain name and? (.*) means nothing or everything”
$ = “this variable will be having everything user entered after the domain name”
In “[R, L]”, “R” means redirect, and “L” means this was the last rule so stop further processing.

Save your “.htaccess” file and you are all done. Stay safe.