As developers, one of the most important things we can do is prevent direct access to your plugin. By this, I mean if someone gets clever and tries to access to one of the files located in any given plugin’s directory, they should not be able to execute any of the code in the script.

Prevent Direct Access To Your Plugin

A simple plugin’s directory from which the below source is pulled.

And I know: This seems like something that’s easy (it is), but even in a recent project, I’m reminded how it’s not something that even some of the most useful plugins do.

I can only chalk this up to lack of awareness or perhaps lack of education. If you’re not setting your work up to prevent direct plugin access to your plugin, you’re leaving a significant security gap in place, and it’s something that can be easily corrected.

Prevent Direct Access To Your Plugin

Before showing the code for how to do this, I want to make sure it’s clear as to why we don’t have people to have direct access to our plugin’s code:

In short, if they can gain access to the scripts, then it’s possible they can execute certain parts of the code that are either outside of the WordPress API or that don’t necessarily do a job of checking if a user has permission to execute a piece of code.

Once they achieve this, the entire site can be compromised. Scary, I know. But no sweat. Making sure that a malicious user can’t gain access to the main plugin file of your plugin is as easy as making sure the first lines of your plugin (below the plugin header) look like this:

There are other precautions to make, as well.

  • You can set permissions to prevent people from viewing the contents of any given directory at the server level.
  • You can place an index.php file in the root of every directory (that will result in a white screen if they attempt to browse a directory.
  • You can make sure that the rest of your functions properly check for nonce values, if a user has permission to execute code, or if the user is even logged into WordPress before executing code.

This is not meant to be a comprehensive post. Far from it.

Instead, it’s meant to be an easy way to prevent people from executing a plugin by running the primary point of entry for many plugins that are running alongside WordPress.

Feel free to share your tips in the comments as this is something that I think is useful for any WordPress developer.

Share:

Leave a Reply