Home >Backend Development >PHP Tutorial >How to Prevent Direct Access to AJAX-Called PHP Files?

How to Prevent Direct Access to AJAX-Called PHP Files?

DDD
DDDOriginal
2024-11-11 07:52:02707browse

How to Prevent Direct Access to AJAX-Called PHP Files?

Intercepting Direct Access to AJAX-Called Files

In AJAX-driven applications, fetching data from server-side PHP scripts requires careful consideration for security. When invoking scripts via GET requests, their contents and parameters become visible to anyone inspecting HTTP headers.

Preventing Direct File Access

To prevent unauthorized users from accessing PHP files directly, we can leverage the HTTP_X_REQUESTED_WITH header sent by AJAX requests. This header indicates that the request originated from an XMLHttpRequest, allowing us to distinguish it from direct access attempts.

Implementation

In your PHP script, add the following code block before any sensitive operations:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
    // Allow access to AJAX requests
} else {
    // Block direct file access and display an error message
    header("HTTP/1.0 403 Forbidden");
    echo "Direct access not permitted.";
}

AJAX Request Header

Your JavaScript code should include the following line to add the X-Requested-With header to AJAX requests:

var xhrobj = new XMLHttpRequest();
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");

This ensures that the server receives the header and correctly identifies the request as an AJAX call. By implementing these measures, you can effectively prevent direct file access to PHP scripts called by AJAX functions, while maintaining accessibility for legitimate AJAX requests.

The above is the detailed content of How to Prevent Direct Access to AJAX-Called PHP Files?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn