Receive JSON POST in PHP

by Vincy. Last modified on February 12th, 2024.

Learning how to receive JSON POST data in PHP from a client program will help to handle the below list of scenarios.

  • When posting bulk data in JSON format to PHP insert multiple rows into the database.
  • When posting a JSON object of photo URLs to a PHP gallery.
  • When sending payment requests to PHP with amount, currency, and more details in a JSON bundle.

View demo

PHP can read the posted JSON data in PHP based on the request methods of the client.

If the JSON data is posted as raw data, then the PHP reads it from the input stream. If it is posted as form data, the $_POST request global can be used in the PHP program to read the posted JSON.

About the examples

In this example, we have created three examples with different client programs posting JSON to see how to read from the PHP endpoint.

  1. Example 1: Use PHP $_POST global variable to read JSON posted via jQuery AJAX.
  2. Example 2: Read JSON posted (via cURL) in PHP using file_get_contents(php://input).
  3. Example 3: Use the  json_decode() without file_get_contents() to read JSON posted via JavaScript XMLHTTPRequest.

All the examples show an HTML form with a textarea to allow the user to enter the JSON. On submission, it posts the data to PHP by different methods using jQuery, JavaScript, or PHP cURL.

Quick example: Read JSON in PHP using $_POST

The below quick example shows the PHP JSON POST data read using the $_POST variable. The jsonData is posted via the jQuery AJAX program.

example1/ep.php

<?php
$data = $_POST['jsonData'];
if ($data !== null) {
    $response = array(
        "responseType" => "success", 
        "response" => $data
);
} else {
    $response = array(
        "responseType" => "error", 
        "response" => "Invalid JSON"
);
}
}
echo json_encode($response);

example1/index.php

function validateJSON(str) {
    try {
        var parsedData = JSON.parse(str);
        // Check if the parsed data is an object
        if (typeof parsedData === 'object' && parsedData !== null) {
            return true;
        }
    } catch (e) {
        return false;
    }
}
$(document).ready(function() {
    $("#form").submit(function(event) {
        event.preventDefault();
        var jsonInput = $("#json_string_input").val();
        $.ajax({
            url: "project root/json-post-php/example1/ep.php",
            type: "post",
            dataType: "json",
            data: {
                jsonData: jsonInput
            },
            complete: function(data) {
                var result = JSON.parse(data["responseText"]);
                if (result && validateJSON(result["response"])) {
                    $("#phppot-message").html("The posted JSON is "+result["response"]);
                    $("#phppot-message").attr("class", result["responseType"]);
                } else {
                    $("#phppot-message").html("Invalid JSON format.");
                    $("#phppot-message").attr("class", "error");
                }
            }
        })
    });
});

The JSON data is from the HTML form. The below index.php file has the form HTML to post the JSON string to PHP.

The on-submit event listener in jQuery posts the JSON input string to PHP via AJAX. The PHP returns the response array with the posted JSON.

In the AJAX complete callback function reads the response array. It validates the JSON in the response and shows a success message with the JSON structure.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receive JSON POST in PHP</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <link href="../form.css" type="text/css" rel="stylesheet" />
    <link href="../style.css" type="text/css" rel="stylesheet" />
</head>

<body>
    <div class="phppot-container">
        <h1>Receive JSON POST in PHP</h1>
        <form action="" method="post" id="form">
            <div id="phppot-message"></div>
            <div class="row">
                <label>Enter JSON data</label>
                <textarea name="json_input" class="full-width" rows="5" cols="50" id="json_string_input"> </textarea>
            </div>
            <div class="row">
                <input type="submit" value="Submit">
            </div>
        </form>
    </div>
</body>

</html>

json post php

2. How to receive JSON data posted via PHP cURL

This example posts the JSON data to PHP via a cURL request. This code is to learn how to send JSON data to an API endpoint with an HTTP POST request.

Once receiving the JSON POST in PHP, it applies the json_custom_validate() function to validate. This function decodes the JSON to execute implicit validation.

If it passes the validation, the PHP code will return a success message or error message “Invalid JSON data”.

In a previous tutorial, we learned PHP cURL POST and saw an example code for it.

example2/index.php

<?php
    $json_data_posted = '';
    $messageType = "";
    $message = "";

    function json_custom_validate($string)
    {
        $postedData = json_decode($string);
        if ($postedData !== null && is_object($postedData)) {
            return true;
        } else {
            return false;
        }
    }
    if (!empty($_POST["submit_json"])) {
        $json_data_posted = $_POST["json_input"];
        // Validate the posted JSON
        if (json_custom_validate($json_data_posted) == false) {
            $messageType = "error";
            $message = "Invalid JSON format.";
        } else {
            // if the JSON is valid post to PHP via cURL
            $url = 'project root/json-post-php/example2/ep.php';

            $data = json_encode($json_data_posted);

            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

            $result = curl_exec($curl);
            curl_close($curl);

            $curlResponse = json_decode($result);

            $messageType = $curlResponse->responseType;
            if ($curlResponse->responseType == 'error') {
                $message = $curlResponse->response;
            } else {
                $message = "The posted JSON data is, " . $curlResponse->response;
            }
        }
    }
    ?>

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="../form.css" type="text/css" rel="stylesheet" />
        <link href="../style.css" type="text/css" rel="stylesheet" />
        <title>Receive JSON POST in PHP</title>
    </head>

    <body>
        <div class="phppot-container">
            <h1>Receive JSON POST in PHP</h1>
            <form action="" method="post">
                <div class="phppot-message <?php echo $messageType; ?>"><?php echo $message; ?></div>
                <div class="row">
                    <lable>Enter JSON data</lable>
                    <textarea name="json_input" class="full-width" rows="5" cols="50"><?php $json_data_posted; ?></textarea>
                </div>
                <div class="row">
                    <input type="submit" name="submit_json" value="Post JSON">
                </div>
            </form>
        </div>
    </body>

    </html>

The cURL POST URL is a PHP endpoint. The below code shows the PHP that reads the raw JSON data. It uses file_get_contents(‘php://input’) to read the JSON resource from the input stream.

example2/ep.php

<?php
$jsonDataPosted = json_decode(file_get_contents('php://input'), true);
if ($jsonDataPosted!== null) {
    $output = array("responseType" => "success", "response" => $jsonDataPosted);
} 
print json_encode($output);
?>

3. How to receive JSON POST sent via JavaScript XMLHttpRequest

The below example posts an XMLHttpRequest via JavaScript. The JS code creates a JSON object and posts it to the PHP.

The algorithm of this code is the same as the example 2. But, it is with plain JavaScript without any libraries.

The JavaScript XMLHttpRequest sets the request and content type. It has the header with content-type=application/json.

The PHP code sends back a response array with the message type and JSON received. The onreadystatechange handle received the response. Then, it updates the user about the result of the JSON read process that happened in the PHP.

example3/index.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receive JSON POST in PHP</title>
    <link href="../form.css" type="text/css" rel="stylesheet" />
    <link href="../style.css" type="text/css" rel="stylesheet" />
</head>
<script>
    function isJson(str) {
        try {
            var parsedData = JSON.parse(str);
            // Check if the parsed JSON data is an object
            return (typeof parsedData === 'object' && parsedData !== null);
        } catch (e) {
            return false;
        }
    }

    function submitForm() {
        var jsonstring = JSON.stringify(document.getElementById("json_string").value);
        ajax = new XMLHttpRequest();
        ajax.onreadystatechange = function() {
            if (ajax.readyState == 4 && ajax.status == 200) {
                var response = ajax.responseText;
                var result = JSON.parse(response);
                if (response && isJson(result["response"])) {
                    document.getElementById("phppot-message").innerHTML = result["response"];
                    document.getElementById("phppot-message").setAttribute("class", result["responseType"]);
                } else {
                    document.getElementById("phppot-message").innerHTML = "Invalid JSON format.";
                    document.getElementById("phppot-message").setAttribute("class", "error");
                }
            }
        }
        ajax.open("POST", "project path/json-post-php/example3/ep.php");
        ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        ajax.send(jsonstring);
    }
</script>

<body>
    <div class="phppot-container">
        <h1>Receive JSON POST in PHP</h1>
        <form action="" method="post" id="form">
            <div id="phppot-message"></div>
            <div class="row">
                <label>Enter JSON data</label>
                <textarea name="json_input" class="full-width" rows="5" cols="50" id="json_string"> </textarea>
            </div>
            <div class="row"><input type="button" value="Submit" id="btnsubmit" onclick="submitForm();"></div>
        </form>
    </div>
</body>

</html>

This function reads the raw JSON data from the request body. It uses the PHP file_get_contents(‘php://input’) and json_encode() to get the JSON string posted.

example3/ep.php

<?php
$data = json_decode(file_get_contents('php://input'), false);
if ($data !== null) {
    $response = array("responseType" => "success", "response" => $data);
}
echo json_encode($response);

View demo Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Receive JSON POST in PHP”

  • HarryPottar says:

    While this is a good base example to get someone started. You’re not handling the case when the json is empty. What if the data is null? You need to define the response for no data first. Then check if the data is null, if not redefine the response

    • Vincy says:

      Hi,

      Thank you for your feedback.

      Now, I have corrected the quick example to handle if the $data == null.

      Keep reading, your comments are always valuable. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page