How to tell if a PHP script is being called by AJAX or from the browser?
The accepted answer to this question says
Modern browsers add the following request header when a request is made using the
XMLHttpRequest
object:X-Requested-With: XMLHttpRequestIn PHP, check the existence of this header using:
$_SERVER['HTTP_X_REQUESTED_WITH']
Bit that does not appear to work in PHP v 7.1.11, Chrome Version 63.0.3239.132 (Official Build) (64-bit)
Is there another way to distinguish?
[Update] I would prefer not to have to add an extra GET
or POST
parameter.
Advertisement
Answer
There is another way is send a GET parameter to tell the page if it is a ajax request such as youpage?ajax. However, there is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.