![]() |
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: Table of Content Using .htaccess to Restrict AccessOne 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> Output: Attempting to access any PHP file directly in the browser will result in a "403 Forbidden" error. Placing Sensitive Files Outside the Web RootAnother effective method involves placing sensitive PHP files outside the web root directory to prevent direct web browser access. /var/www/html/ // Web root
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 AccessYou 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:
config.php:
Output: Attempting to access config.php directly in the browser will display the message "Direct access not permitted." Restricting Access in PHP CodeYou can also restrict access directly within the PHP files by checking the server variables.
Output: Direct access attempt to the PHP file will result in:Direct access not permitted Changing the Server ConfigurationFor servers other than Apache, such as Nginx, you can configure the server to restrict access to PHP files. Example: location ~* \.php$ { Output: When attempting to access a PHP file directly via a web browser, you will see:403 Forbidden |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 22 |