What are the differences between WPINC and ABSPATH?

It’s common for plugin developers to protect their plugins from direct access. I saw two ways to do that:

if ( ! defined( 'WPINC' ) ) die;

and

Read More
if ( ! defined( 'ABSPATH' ) ) exit;

What are the differences between WPINC and ABSPATH? Which one is the ‘right’ way to do it?

Related posts

3 comments

  1. They are defined as follows:

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

    dirname is a PHP function that returns the path of the parent directory, and wp-includes is pretty self explanatory.

    I would say ABSPATH is better because it’s one of the first things WP loads and it also looks better:) But there is no real “right way” because they both work.

  2. if ( ! defined( 'WPINC' ) ) die; and if ( ! defined( 'ABSPATH' ) ) exit; add an extra layer of security by preventing any direct access to your plugin file. ABSPATH is a PHP constant defined by WordPress in its core.

    If your plugin file is accessed from outside of WordPress, the constant ABSPATH or WPINC will not be defined, so it exits the plugin code, preventing any unauthorized access to your code.

    ABSPATH and WPINC are defined in WordPress core as:

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

    Both are used for same purpose.

  3. What are the differences between WPINC and ABSPATH?

    You can check yourself. Just look at wp-load.php on the WordPress mirror on GitHub.

    Even a quick glance will show the currently selected answer is no longer correct as to how ABSPATH is defined. And if you compare different tags on GitHub you will see the ABSPATH definition actually changes over time.

    Which one is the ‘right’ way to do it?

    Given these are used for security, I’d go for ABSPATH. Rationale being that ABSPATH is not only defined first in the WP bootstrapper, WPINC is defined under a conditional in the same file and, as a result, is more likely to experience a future regression.

    Also, while not explicitly asked, you provided examples using both die and exit. According to devdocs.io, which draws on official API documentation, die is equivalent to exit, so you could choose either of the two and it won’t make a difference.

    Both die and exit accept arguments, so you could consider using them to output some useful information, such as an encrypted version tag or contact information, upon abend, or pass an exit code such as 0 or -1 for further processing.

    Also worth noting is that wp_die is a thing too. Not to be confused with the PHP built-ins, but compliments them for use in outputting HTML in addition to plain text and is used liberally throughout the WordPress core currently. Learn more about wp_die on WordPress.org.

Comments are closed.