2

I am developing a WordPress plugin, but before that I have checked the code for the few plugin already developed. I have seen a common approach to restrict the direct where the plugin developer starts the plugin code by the following line

//  If accessed directly, abort
if ( ! defined( 'WPINC' ) ) {
    die;
}

This is in the plugin index file. My question is when we install the plugin this is the first file to be executed so where it is defined before and it is not abort the execution on the file ?

4

Question 1. so where it is defined before
Answer:

It is defined in WordPress core.

Here a quick online reference or for a local reference take a look at the following file in the root of WordPress: wp-settings.php. In that file (around line 18) following code is shown:

define( 'WPINC', 'wp-includes' );


Question 2. and it is not abort the execution on the file
Answer:

The use (the goal so to say) of it is to protect plugins from direct access
(from the outside, preventing any unauthorized access to your code)
Two ways to achieve this protection, some developers use WPINC and others use ABSPATH as in:

  • if (!defined('ABSPATH')) exit; (or replace exit with die("No cheating!") or other txt)
  • if ( ! defined( 'WPINC' ) ) die; (or use exitin same way as above)

Both defined as follow:

  • define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' );
  • define( 'WPINC', 'wp-includes' );

dirname (generic PHP) simply returns the directory from a full path.
wp-includes is pretty self explanatory.


You are free to decide which to use. I personally think there is no real right way , both have the same purpose. I use only ABSPATH but it is all up to your personal preference.
Just remember to add it directly below the header section or at least near the top of your plugin.

1

WPINC is defined by WP before plugins are loaded; so, the fact that it is already defined indicates the plugin is being loaded by WP rather than a direct request.

0

You can also use this one as well. It is defined in Akismet Anti-Spam Plugin.

// Make sure we don't expose any info if called directly
if ( !function_exists( 'add_action' ) ) {
    echo 'Hi there!  I\'m just a plugin, not much I can do when called directly.';
    exit;
}
  • 1
    It is better if you refer the original author akismet. – user2584538 Dec 19 '18 at 12:26
  • why? what's the improvement? been searching for a while, and found no arguments for this. Some big plugins do this tho – pcarvalho Jan 10 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.