Graviton
Graviton

Reputation: 83274

PHP check whether incoming request is JSON type

Is there anyway to check whether an incoming request is of AJAX JSON type?

I tried

if(($_SERVER['REQUEST_METHOD']=='JSON'))
{
}

But it didn't work.

Any thoughts?

Upvotes: 11

Views: 21596

Answers (6)

AriehGlazer
AriehGlazer

Reputation: 2320

you can always set an extra header specifying that, or use an arbitrary variable to indicate JSON requests.

Upvotes: -1

karim79
karim79

Reputation: 342685

You would need to set a header from the client side. jQuery and other libraries set a x-requested-with header:

if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
   echo "Ajax request";
}

Upvotes: 13

Anthony
Anthony

Reputation: 37065

Where are you accepting requests from, exactly, that you wouldn't know?

You could have a function at the beginning of the script that tries to import the data as JSON or simplexml. If it catches an error, you know it's the other one...

On second thought, have it test it to be JSON, simplexml will throw an error for tons of reasons.

 $json_request = (json_decode($request) != NULL) ? true : false;

Upvotes: 12

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827724

You can check the X-Requested-With header, some libraries, like jQuery set it to "XMLHttpRequest".

$isAjaxRequest = $_SERVER['X_REQUESTED_WITH'] == 'XMLHttpRequest';

Upvotes: 4

Deniss Kozlovs
Deniss Kozlovs

Reputation: 4841

Try json_decode()

Upvotes: -2

kristian nissen
kristian nissen

Reputation: 2907

You can do a check on the accept param, if it's text/javascript your talking json, if it's text/xml guess what :P

$_SERVER['HTTP_ACCEPT']

Upvotes: 4

Related Questions