Preventing Direct Access to Files Accessed via AJAX
When accessing a PHP file through an AJAX request, such as "func.php", direct access to that file can be a security concern. To address this issue, it's crucial to implement a mechanism that differentiates between AJAX requests and direct access attempts.
One effective solution is to leverage the "HTTP_X_REQUESTED_WITH" server variable. Most AJAX frameworks set this header to "XMLHttpRequest", providing a way to distinguish between genuine AJAX requests and direct browser access. This header check can be implemented in the PHP file as follows:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) { // Allow access... } else { // Ignore or deny access... }
By implementing this check, you can ensure that only legitimate AJAX requests can access the specified file, protecting it from unauthorized direct access.
Additionally, for enhanced security, you can manually set the "X-Requested-With" header in your AJAX request using the following JavaScript code:
var xhrobj = new XMLHttpRequest(); xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
This step further strengthens the protection against direct file access.
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