Intro

Direct access to PHP files using a URL (for example, through a browser) can lead to unexpected results.

This is because, on a WordPress site, these files can include other functions that will not work or constants that will not be available in direct access but only in the context of WordPress.

Depending on the code, this can lead to server-side errors or even data leaks.

Hence, it is recommended to prevent such access by adding this simple code to the top of your theme/plugin files.

Implementation

Add the following code to the top of the PHP file:

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

This can be placed after the top comments, for example:

/**
 * Theme/plugin file
 *
 * @package ProjectName
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

Another (short) version:

defined( 'ABSPATH' ) || exit;

How it works

The built-in configuration file in WordPress (wp-config.php) creates the ABSPATH constant:

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}

So if the ABSPATH constant doesn’t exist, it means that the WordPress environment is not running.

In other words, if a user tries to access a PHP file directly (not in the context of WordPress), this constant would not exist, since the wp-config.php file is not triggered.

In this case, this code snippet will stop the rest of the PHP script from loading (using the exit function).