Using JSON AJAX posts from PHP

Because I know I’ll need this again in the future, here’s how to use an AJAX request with a JSON body (such as how an AngularJS $resource posts) from within PHP:

if (
	array_key_exists('CONTENT_TYPE', $_SERVER)
	&& array_key_exists('CONTENT_LENGTH', $_SERVER)
	&& (strncmp($_SERVER['CONTENT_TYPE'], 'application/json', 16) === 0)
	&& (intval($_SERVER['CONTENT_LENGTH']) < 10000)
   ) {
	try {
		$bodyData = json_decode(file_get_contents('php://input'), TRUE);
		if (is_array($bodyData)) {
			foreach ($bodyData as $bodyKey => $bodyValue) {
				$this->context->{$bodyKey} = $bodyValue;
	} catch (\Exception $e) {
		// no fallback here

As you can see, there’s some paranoia in there to avoid reading posts with more than 10K of data. If your client isn’t using application/json as its MIME type then you may need to fiddle with it. But keep in mind that the client may be more verbose with the MIME type, such as application/json;charset: your-mom, so you can’t just do a simple string comparison. And, of course, you’ll want to swap out the loop for something meaningful for your situation.

Categorized as AJAX, Web

By Rick Osborne

I am a web geek who has been doing this sort of thing entirely too long. I rant, I muse, I whine. That is, I am not at all atypical for my breed.