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
Release: 2024-11-13 00:42:02
Original
846 people have browsed it

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
}
Copy after login

In Javascript code, you can set this header manually:

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template