Where o where is $_JSON?

Blog  — Fri 16 Jun 2023

This blog article is for programmers. If you're not a programmer, I think it's better for you to skip this one.

So, before we begin. I must admit, we're venturing into uncharted territory with this daring statement of mine. Brace yourself, for here it comes, armed with a sprinkle of humor to keep things light during a very serious technical question;


Yes, folks, behold the audacity! I present to you the latest sensation I hope will once sweep the nation; $_JSON!

Now, before you raise an eyebrow or two, hear me out. We've witnessed the rise of $_POST, a formidable hero that tames "application/x-www-form-urlencoded" content, and the mighty $_FILES, vanquishing "multipart/form-data" like a true champion. Remarkably, PHP even boasts the ability to handle both $_POST and $_FILES simultaneously if the "multipart/form-data" is feeling feisty!

But, dear adventurers, when it comes to posting JSON, be prepared for an exhilarating ride. Well, perhaps I've embellished it slightly. Nevertheless, at the bare minimum, you'll find yourself doing something like this:

$raw_posted_json = file_get_contents('php://input');
$_JSON = json_decode($raw_posted_json, true);

Now, let's address the paradox. Although $_POST is intended for form data, when you post JSON, you still use the good ol' HTTP POST method. Therefore, if your CONTENT_TYPE is happily set to "application/json," it's safe to assume that the elusive "application/x-www-form-urlencoded" or "multipart/form-data" won't come galloping in. One could even be audacious enough to employ the following code snippet:

    isset($_SERVER["CONTENT_TYPE"]) &&
    $_SERVER["CONTENT_TYPE"] === 'application/json'
) {
    $raw_posted_json = file_get_contents('php://input');
    $_POST = json_decode($raw_posted_json, true);

I must acknowledge that file_get_contents('php://input') is more versatile than just handling JSON. However, JSON has nestled itself cozily in the hearts of developers over the years. It conquered the realm of API exchanges, becoming the de facto standard. Even frontends and backends engage in chitchats using JSON. Oh, the irony! JavaScript took it and ran with it, pun wholeheartedly intended.

So, will 2023 be the year of official support for $_JSON in PHP? I sure wouldn't mind.