"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Prevent Direct Access to Files Called by Ajax?

How to Prevent Direct Access to Files Called by Ajax?

Published on 2024-11-10
Browse:572

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");
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3