Not Allowing Direct Access To PHP Files

Not Allowing Direct Access To PHP files

You can use several methods to not allow web surfers to access files directly. One method can be done with an Apache configuration or .htaccess and another is to define a constant in a file and include the other file while making sure the constant was defined.

Method #1 Apache and .htaccess

With this method, you name your more sensitive include files with an extension like '.inc', or even better '.inc.php'. Then, you add a little code into the .htaccess file so that it cannot be accessed directly through the browser or by bots, etc.

 <Files ~ ".inc"> Order allow,deny Deny from all </Files> 

Method #2 Constants

In one file, you can define the constant my_pdo and include the file you want to protect.

File #1

 define('my_pdo', true); include("";  

File #2
In the other file, you do a simple check by adding the following code to the top. As you can see, it will die and print out a message if it is accessed directly.

 if(!defined('my_pdo')) {     die('Direct access not permitted'); }