Home > Backend Development > PHP Tutorial > How to Prevent Direct Access to Files Accessed via AJAX?

How to Prevent Direct Access to Files Accessed via AJAX?

DDD
Release: 2024-11-18 00:19:02
Original
973 people have browsed it

How to Prevent Direct Access to Files Accessed via AJAX?

How to Prevent Direct Access to a File Accessed via AJAX

When constructing AJAX requests, it is crucial to ensure the security of the data being transferred. If the request method is GET, the data can be easily viewed by examining the request headers. While the solution provided in the mentioned duplicate question does not seem to resolve the issue, there is an alternative approach that can effectively prevent direct access to the target file.

Solution:

To selectively grant access to AJAX requests while denying direct access to the file, you can leverage the HTTP_X_REQUESTED_WITH server variable. This variable is set to XMLHttpRequest by most AJAX frameworks and libraries. Using this variable, you can implement the following check within the PHP file (e.g., func.php):

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
    // Allow access since this is an AJAX request
} else {
    // Deny access since this is a direct request
}
Copy after login

Integrating the Header:

To ensure that your AJAX request includes the X-Requested-With header, add the following line to your JavaScript code before sending the request:

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
Copy after login

Effectiveness:

By implementing this solution, you effectively restrict direct access to the target file while allowing AJAX requests from authorized sources. This helps prevent potential abuse of data or security breaches.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template