Security should be one of the (if not the) most important aspects of your plugin. Ironically it’s also one of the most difficult parts to explain. There’s no ‘quick fix’ to writing a secure plugin. There are so many aspects to writing a secure plugin and on top of that it’s an ever changing game. Luckily there are some tips that can help make your plugin more secure and one of them is disabling direct file access to your plugin files. Please note that solely preventing direct access to your files doesn’t make your plugin secure but it does help in making it more secure.
What is direct file access
Direct file access is when someone directly queries your file. This can be done by simply entering the complete path to the file in the URL bar of the browser but can also be done by doing a POST request directly to the file. For files that only contain a PHP class the risk of something funky happening when directly accessed is pretty small. For files that contain procedural code, functions and function calls, the chance of security risks is a lot bigger.
Preventing direct file access
Luckily it’s easy to prevent direct access to your files. In your wp-config.php
file the constant ABSPATH
is set. By checking if the constant is set at the top of your plugin file you can check if your wp-config.php
file was loaded what should mean that WordPress is loaded. If your file is directly accessed this won’t be the case and the script will abort. Adding this code snippet to the top of your files will prevent direct file access to them.
Not sure if your files are directly accessible? Be sure to check them! I hope this helped you in making your plugin more secure. Missing something? Found a problem? Got an improvement? Please let me know in the comments below.
This is one of the best ways of preventing direct access to WordPress plugin files. Thanks for posting!
Glad to hear you like it 🙂
Simple and very usefull!
Thanks!
Happy to help! 🙂
I take pleasure in, result in I found just what I was having
a look for. You have ended my 4 day long hunt! God Bless you man. Have a nice day.
Bye
Regarding direct access, why are class-only files at less risk than procedural-type files?
[…] In this particular instance the plugin wasn’t even active, just laying dormant on the website. This emphasises how important it is to delete any unused plugins, as they can still be executed even when not active. You can read more at WordPress Housekeeping. This is also a reminder to developers to make sure cannot be executed outside of the WordPress environment. […]
Good explanation.
What about theme php files? Should be secured in the same way?