Learn how to prevent direct access to PHP files in WordPress to safeguard your website’s security. This simple guide helps you block unauthorized access, ensuring the safety of your themes and plugins.
Open any plugin’s PHP file straight in your browser and, on a bad day, you get a stack trace with a full server path in it. Not a hack, just a leak. The one-line fix has been in the WordPress developer handbook for years, and you should paste it into every PHP file you write.
Why direct access matters
A PHP file is meant to run inside WordPress, after core has booted. Hit it directly by its URL and it runs with none of that context loaded. Best case it does nothing useful. Worst case a fatal error prints a file path, a database detail, or some half-initialized output that tells an attacker where to poke next. You want the file to just stop.
The guard
Put this at the very top of the file, right after the opening PHP tag:
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}ABSPATH is defined by WordPress when it loads. If it’s missing, nobody loaded WordPress, so the file was called directly and exit bails before a single line of your logic runs. Some people write it as exit;, some as die;. They do the same thing here.
Where to put it
Every PHP file, not just the main plugin file. Open the file, drop the guard in as the first statement, save. Do it for includes, class files, template partials, all of them. It’s cheap and it’s habit, not a decision you make per file.
One honest caveat
This stops direct execution and the info leaks that come with it. That’s all it does. It is not access control. It won’t check who the user is or verify a form submission, so it doesn’t replace capability checks and nonces on anything that changes state. Think of it as the lock on a door that should never have been a public entrance, not the security for the rooms behind it.


