Home > Article > Backend Development > 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!