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 }
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");
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!