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