Block direct access to PHP file except from AJAX request?

后端 未结 2 505
清歌不尽
清歌不尽 2021-01-01 06:41

I wish to have a webpage that uses AJAX to access a PHP file in ./ajax/file.ajax.php

Trouble is, I don\'t want people to be able to type the address in

2条回答
  •  情书的邮戳
    2021-01-01 07:00

    If you're using jQuery to make the XHR, it will set a custom header X-Requested-With. You can check for that and determine how to serve your response.

    $isXhr = isset($_SERVER["HTTP_X_REQUESTED_WITH"])
             AND strotlower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest";
    

    However, this is trivial to spoof. In the past, I've used this to decide whether to render a whole page (if not set) or a page fragment (if set, to be injected into current page).

提交回复
热议问题