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
if ( ! defined( 'ABSPATH' ) ) exit;
What are the differences between WPINC and ABSPATH? Which one is the ‘right’ way to do it?
They are defined as follows:
dirname
is a PHP function that returns the path of the parent directory, andwp-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.if ( ! defined( 'WPINC' ) ) die;
andif ( ! 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
orWPINC
will not be defined, so it exits the plugin code, preventing any unauthorized access to your code.ABSPATH
andWPINC
are defined in WordPress core as:Both are used for same purpose.
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 theABSPATH
definition actually changes over time.Given these are used for security, I’d go for
ABSPATH
. Rationale being thatABSPATH
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
andexit
. According todevdocs.io
, which draws on official API documentation,die
is equivalent toexit
, so you could choose either of the two and it won’t make a difference.Both
die
andexit
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 as0
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 aboutwp_die
on WordPress.org.