PHP check whether Incoming Request is JSON type PHP check whether Incoming Request is JSON type php php

PHP check whether Incoming Request is JSON type


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;


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";}


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']