0

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: XMLHttpRequest

In 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.

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551
  • 1
    _"I would prefer not to have to add an extra GET or POST parameter"_ - that leaves - your own request header. Many popular frameworks explicitly add one of their own, to make sure they don't have to rely on the browser sending anything that could make an AJAX request distinguishable from a "normal" one itself. – CBroe Jan 07 '18 at 11:13
  • Weeeell, I *could*, but, again, I would prefer to leave the code unchanged, and just find a way to distinguish browser instated requests (there are no security concerns, this is just development code which will be ripped out long before production). +1 for the tip, though – Mawg says reinstate Monica Jan 07 '18 at 11:43

2 Answers2

1

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.

Ngo Tuan
  • 205
  • 1
  • 2
  • 16
  • 1
    I needed to know this for a former project and also spoofed the user agent when making a Ajax call. – DigiLive Jan 07 '18 at 09:47
  • 3
    Yeah, it is no difficult to spoof the user agent so i think there is no way to tell certainly if a request com.from ajax or not – Ngo Tuan Jan 07 '18 at 09:53
  • GET or POST, yeah, I had figured that, but preferred to avoid it. I will upvote you & update the question. – Mawg says reinstate Monica Jan 07 '18 at 11:10
  • Surely, if you want to distinguish console access, where the user can see the source, and from the browser's URL bar, then you use a somewhat unguessable parameter to distinguish? If absent, request is AJAX; if URL includes `?rgyfgueguy4f6edw`, then it was you from the browser. Since the user has no access to your server-side code, they are unlikely to guess that the magic string is `rgyfgueguy4f6edw` – Mawg says reinstate Monica Jan 07 '18 at 11:14
  • 1
    Can you accept my answer. I'm trying get reputation for my exam on class – Ngo Tuan Jan 07 '18 at 11:32
0

See here.

if (empty($_SERVER['HTTP_X_REQUESTED_WITH']))  // Ajax

is working for me

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551