prevent direct access to php files

How to Prevent Direct Access to PHP File

Sometimes you may need to prevent direct access to PHP file on your website. In this artice, we will look at how to prevent PHP file from direct URL access.


How to Prevent Direct Access to PHP File

Here are the steps to prevent direct access to PHP file. Let us say you have a PHP file /form.php at /var/www/html/form.php and it is executed during a form submission on your website http://example.com. Let us say that you don’t want people to access your PHP file directly at http://example.com/form.php. In such cases, follow the steps below.


1. Open PHP file in a text editor

Open terminal and run the following command to open form.php in a text editor.

$ sudo vi /var/www/html/form.php


2. Prevent Direct Access to PHP file

Add the following lines to the top of your PHP file.

<?php
    if ( $_SERVER['REQUEST_METHOD']=='GET' && realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {        
        header( 'HTTP/1.0 403 Forbidden', TRUE, 403 );
        die( header( 'location: /index.php' ) );
    }
?>

Let us look at the above code line by line.

In the first line, we have an if condition where we check if the request method is GET and if the absolute path of the file is same as the full path of the requested file.

In such cases, the server will call header function to return 403 access forbidden response code. You may also use 404 page not found code instead to avoid giving any hints to malicious users about the authenticity of requested URL.

Lastly, we use the die function to exit the page and redirect to index.php page that is home page. You may also redirect to another page as per your requirement.


If the above code does not work for you, you may add the following code to the top of your file form.php instead.

if(!isset($_SERVER['HTTP_REFERER'])){
    // redirect them to your desired location
    header('location: /index.php');
    exit;
}

The above code basically tests if the HTTP_REFERER header of request is set or not. If it is not set, as is the case with plain GET requests sent from browsers, then it will redirect users to home page.


3. (Optional) Restart Apache Server

Restart Apache server to apply changes. This will help clear any cached pages.

$ sudo service apache2 restart

Now when a user tries to access /form.php via GET request on a browser or CLI then they will be redirected to home page.

Also read :

How to Fix NGINX Upstream Timed Out Error
How to Download File from NodeJS Server
How to Fix Errno 13 Permission Denied Error in Django
How to Install more_set_headers in NGINX
How to Get Data from URL in NodeJS


2 thoughts on “How to Prevent Direct Access to PHP File

Leave a Reply

Your email address will not be published. Required fields are marked *