Home >Backend Development >PHP Tutorial >How to Prevent Direct Access to Files Called by Ajax?

How to Prevent Direct Access to Files Called by Ajax?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 00:42:02853browse

How to Prevent Direct Access to Files Called by Ajax?

How to Restrict Direct Access to Files Called by Ajax

When utilizing Ajax to invoke PHP code, as illustrated in the query, the data being transmitted can be vulnerable to exposure through examining request headers. While the data may not be confidential, its potential for exploitation remains.

To address this concern, a common solution involves utilizing the HTTP_X_REQUESTED_WITH header. This header, typically set by Ajax requests/frameworks, enables differentiation between Ajax and non-Ajax requests. The following code snippet showcases its implementation:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
    // Allow access within Ajax requests
} else {
    // Block access outside of Ajax requests
}

In Javascript code, you can set this header manually:

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

The above is the detailed content of How to Prevent Direct Access to Files Called by Ajax?. 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