Prevent direct access to PHP file content and allow only via AJAX call

Sometimes it is necessary to protect your PHP file from direct access that is calling via AJAX request. The most important reason behind it is the security. If a file calling only via AJAX then it is better to disable it from direct access for security reason.

In web technology, it is always said that allow only those which is necessary. It is applicable for any types of file, code, part of the code, directory and so on.

Send AJAX request every n seconds using jQuery

Ajaxify Weather Forecast PHP Script Source Code

Now here we are going to see how to prevent direct access to a PHP file content so that it can only access through AJAX call. Well, there is nothing complicated in doing this task. It just needs to check a simple condition.

We are going to use the PHP global variable $_SERVER. Below is simple if else condition which will check if the file is calling via AJAX request or not and on depending upon this it will run the code:

if( isset( ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) && $_SERVER['HTTP_X_REQUESTED_WITH'] ) )
    // Code that will run if this file called via AJAX request
} else {
    // Code that will run when accessing this file directly

IN the above code we are checking if $_SERVER[‘HTTP_X_REQUESTED_WITH’] and $_SERVER[‘HTTP_X_REQUESTED_WITH’] headers are set or not to check if request coming from AJAX or not.

Process form value in PHP using jQuery AJAX method

Well most of the AJAX request including jQuery AJAX set this particular header. We can use it to see if the request coming to the file through AJAX or not and we can let our code run only the request come from AJAX.

One response to “Prevent direct access to PHP file content and allow only via AJAX call”

  1. GRE Development says:

    It’s not 100% secure!

    You can send requests without Ajax by editing the headers of per request 😉

Leave a Reply

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