Sometimes, we want to prevent direct access to a PHP include file.
In this article, we’ll look at how to prevent direct access to a PHP include file.
How to prevent direct access to a PHP include file?
To prevent direct access to a PHP include file, we can check if the file that includes the current script has the variable we’re looking for.
For instance, we write
if (!defined("MyConst")) {
die("Direct access not permitted");
}
in the current script to check if MyConst
is defined.
If not, we call die
to stop the script.
Then in the script that we want to include the script, we define MyConst
with
define("MyConst", true);
Conclusion
To prevent direct access to a PHP include file, we can check if the file that includes the current script has the variable we’re looking for.