Getting plugged in - part two: security

The security of any code should be of the utmost importance but, if creating a plugin that might be distributed to other people's sites, it should be paramount.

It's one thing messing up your own site but another entirely breaking someone else's when they've put their trust in what you've written.

As we established last time, this series covers the process of improving my "Likes and Replies" WordPress plugin. This is a relatively simple piece of code that doesn't do much (yet) but it's still good to ensure it's as secure as it can be and get into good habits.

First steps

It is best practice to prevent direct access to plugin files meaning they can only be used within the context of a WordPress installation. This is done by adding the following to the start of any PHP files:

if (!defined('ABSPATH')) exit; // Don't run if accessed directly

ABSPATH is the absolute path to the WordPress installation directory and is defined by WordPress itself. If this is not available to the plugin it is not being run within the context of an installation.

We are relying on user input in the form of a URL to add likes or replies so should take steps to ensure that this is properly encoded and valid. We can use esc_url() to do this which removes invalid or dangerous characters.

Getting the address entered into the custom field then becomes:

$mentionurl = esc_url(get_post_meta($id, $type, true));

I had already made a change to the code replacing file_get_contents() with wp_remote_get() as the former was considered insecure.

A good start

With a more complex plugin additional protection may be required, like sanitising inputs which I, no doubt, will have to do later if I am able to meet my goals.

This is a good start to the learning process but I now need to work on my priorities for what to tackle next.

2 comments: click to readComments

Colin Walker Colin Walker colin@colinwalker.blog