Open In App

How to Prevent Direct Access to PHP Files?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn about Preventing direct access to PHP files. Preventing direct access to PHP files is crucial for securing a web application. PHP files intended for inclusion in other scripts should not be accessible directly via a web browser.

There are several methods to prevent direct access to the PHP files which are as follows:

Using .htaccess to Restrict Access

One of the most common methods for preventing direct access to PHP files is by using a .htaccess file if you are running an Apache server. This method is advantageous for protecting multiple files within a directory.

Example: Blocking access to all PHP files within a directory:

<Files *.php>    
Order Allow, Deny
Deny from all
</Files>

Output:

Attempting to access any PHP file directly in the browser will result in a "403 Forbidden" error.

Placing Sensitive Files Outside the Web Root

Another effective method involves placing sensitive PHP files outside the web root directory to prevent direct web browser access.

/var/www/html/             // Web root
/var/www/includes/ // Directory outside the web root
PHP
<?php
include '/var/www/includes/config.php';
?>

Output:

Files in /var/www/includes/ are not accessible directly via the web browser, enhancing security by preventing direct access.

Using a Constant to Check Direct Access

You can define a constant in your main PHP script and check for its presence in your included files. This ensures that the included files are not accessed directly.

index.php file:

PHP
<?php
define('SECURE_ACCESS', true);
include 'includes/config.php';
?>

config.php:

PHP
<?php
if (!defined('SECURE_ACCESS')) {
    die('Direct access not permitted');
}
// Rest of your code
?>

Output:

Attempting to access config.php directly in the browser will display the message "Direct access not permitted."

Restricting Access in PHP Code

You can also restrict access directly within the PHP files by checking the server variables.

PHP
<?php
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
    die('Direct access not permitted');
}
// Rest of your code
?>

Output:

Direct access attempt to the PHP file will result in:Direct access not permitted

Changing the Server Configuration

For servers other than Apache, such as Nginx, you can configure the server to restrict access to PHP files.

Example:

location ~* \.php$ {
deny all;
return 403;
}

location /index.php {
allow all;
}

Output:

When attempting to access a PHP file directly via a web browser, you will see:403 Forbidden

Article Tags :

Similar Reads