Friday, March 1, 2024
HomePHPObtain JSON POST in PHP

Obtain JSON POST in PHP


by Vincy. Final modified on February 4th, 2024.

Studying the right way to obtain JSON POST knowledge in PHP from a shopper program will assist to deal with the beneath listing of situations.

  • When posting bulk knowledge in JSON format to PHP insert a number of rows into the database.
  • When posting a JSON object of picture URLs to a PHP gallery.
  • When sending fee requests to PHP with quantity, forex, and extra particulars in a JSON bundle.

View demo

PHP can learn the posted JSON knowledge in PHP based mostly on the request strategies of the shopper.

If the JSON knowledge is posted as uncooked knowledge, then the PHP reads it from the enter stream. Whether it is posted as kind knowledge, the $_POST request world can be utilized within the PHP program to learn the posted JSON.

In regards to the examples

On this instance, we’ve got created three examples with completely different shopper applications posting JSON to see the right way to learn from the PHP endpoint.

  1. Instance 1: Use PHP $_POST world variable to learn JSON posted by way of jQuery AJAX.
  2. Instance 2: Learn JSON posted (by way of cURL) in PHP utilizing file_get_contents(php://enter).
  3. Instance 3: Use the  json_decode() with out file_get_contents() to learn JSON posted by way of JavaScript XMLHTTPRequest.

All of the examples present an HTML kind with a textarea to permit the person to enter the JSON. On submission, it posts the info to PHP by completely different strategies utilizing jQuery, JavaScript, or PHP cURL.

Fast instance: Learn JSON in PHP utilizing $_POST

The beneath fast instance exhibits the PHP JSON POST knowledge learn utilizing the $_POST variable. The jsonData is posted by way of the jQuery AJAX program.

example1/ep.php

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

example1/index.php

operate validateJSON(str) {
    attempt {
        var parsedData = JSON.parse(str);
        // Test if the parsed knowledge is an object
        if (typeof parsedData === 'object' && parsedData !== null) {
            return true;
        }
    } catch (e) {
        return false;
    }
}
$(doc).prepared(operate() {
    $("#kind").submit(operate(occasion) {
        occasion.preventDefault();
        var jsonInput = $("#json_string_input").val();
        $.ajax({
            url: "venture root/json-post-php/example1/ep.php",
            kind: "submit",
            dataType: "json",
            knowledge: {
                jsonData: jsonInput
            },
            full: operate(knowledge) {
                var consequence = JSON.parse(knowledge["responseText"]);
                if (consequence && validateJSON(consequence["response"])) {
                    $("#phppot-message").html("The posted JSON is "+consequence["response"]);
                    $("#phppot-message").attr("class", consequence["responseType"]);
                } else {
                    $("#phppot-message").html("Invalid JSON format.");
                    $("#phppot-message").attr("class", "error");
                }
            }
        })
    });
});

The JSON knowledge is from the HTML kind. The beneath index.php file has the shape HTML to submit the JSON string to PHP.

The on-submit occasion listener in jQuery posts the JSON enter string to PHP by way of AJAX. The PHP returns the response array with the posted JSON.

Within the AJAX full callback operate reads the response array. It validates the JSON within the response and exhibits a hit message with the JSON construction.

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

<head>
    <meta charset="UTF-8">
    <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Obtain JSON POST in PHP</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <hyperlink href="https://phppot.com/php/json-post-php/kind.css" kind="textual content/css" rel="stylesheet" />
    <hyperlink href="http://phppot.com/fashion.css" kind="textual content/css" rel="stylesheet" />
</head>

<physique>
    <div class="phppot-container">
        <h1>Obtain JSON POST in PHP</h1>
        <kind motion="" methodology="submit" id="kind">
            <div id="phppot-message"></div>
            <div class="row">
                <label>Enter JSON knowledge</label>
                <textarea identify="json_input" class="full-width" rows="5" cols="50" id="json_string_input"> </textarea>
            </div>
            <div class="row">
                <enter kind="submit" worth="Submit">
            </div>
        </kind>
    </div>
</physique>

</html>

json post php

2. How one can obtain JSON knowledge posted by way of PHP cURL

This instance posts the JSON knowledge to PHP by way of a cURL request. This code is to discover ways to ship JSON knowledge to an API endpoint with an HTTP POST request.

As soon as receiving the JSON POST in PHP, it applies the json_custom_validate() operate to validate. This operate decodes the JSON to execute implicit validation.

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

In a earlier tutorial, we discovered PHP cURL POST and noticed an instance code for it.

example2/index.php

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

    operate 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 legitimate submit to PHP by way of cURL
            $url="venture root/json-post-php/example1/ep.php";

            $knowledge = 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, $knowledge);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content material-Sort: utility/json'));

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

            $curlResponse = json_decode($consequence);

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

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

    <head>
        <meta charset="UTF-8">
        <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
        <hyperlink href="https://phppot.com/php/json-post-php/kind.css" kind="textual content/css" rel="stylesheet" />
        <hyperlink href="http://phppot.com/fashion.css" kind="textual content/css" rel="stylesheet" />
        <title>Obtain JSON POST in PHP</title>
    </head>

    <physique>
        <div class="phppot-container">
            <h1>Obtain JSON POST in PHP</h1>
            <kind motion="" methodology="submit">
                <div class="phppot-message <?php echo $messageType; ?>"><?php echo $message; ?></div>
                <div class="row">
                    <lable>Enter JSON knowledge</lable>
                    <textarea identify="json_input" class="full-width" rows="5" cols="50"><?php $json_data_posted; ?></textarea>
                </div>
                <div class="row">
                    <enter kind="submit" identify="submit_json" worth="Publish JSON">
                </div>
            </kind>
        </div>
    </physique>

    </html>

The cURL POST URL is a PHP endpoint. The beneath code exhibits the PHP that reads the uncooked JSON knowledge. It makes use of file_get_contents(‘php://enter’) to learn the JSON useful resource from the enter stream.

example2/ep.php

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

3. How one can obtain JSON POST despatched by way of JavaScript XMLHttpRequest

The beneath instance posts an XMLHttpRequest by way of JavaScript. The JS code creates a JSON object and posts it to the PHP.

The algorithm of this code is similar as the instance 2. However, it’s with plain JavaScript with none libraries.

The JavaScript XMLHttpRequest units the request and content material kind. It has the header with content-type=utility/json.

The PHP code sends again a response array with the message kind and JSON obtained. The onreadystatechange deal with obtained the response. Then, it updates the person about the results of the JSON learn course of that occurred within the PHP.

example3/index.php

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

<head>
    <meta charset="UTF-8">
    <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Obtain JSON POST in PHP</title>
    <hyperlink href="https://phppot.com/php/json-post-php/kind.css" kind="textual content/css" rel="stylesheet" />
    <hyperlink href="http://phppot.com/fashion.css" kind="textual content/css" rel="stylesheet" />
</head>
<script>
    operate isJson(str) {
        attempt {
            var parsedData = JSON.parse(str);
            // Test if the parsed JSON knowledge is an object
            return (typeof parsedData === 'object' && parsedData !== null);
        } catch (e) {
            return false;
        }
    }

    operate submitForm() {
        var jsonstring = JSON.stringify(doc.getElementById("json_string").worth);
        ajax = new XMLHttpRequest();
        ajax.onreadystatechange = operate() {
            if (ajax.readyState == 4 && ajax.standing == 200) {
                var response = ajax.responseText;
                var consequence = JSON.parse(response);
                if (response && isJson(consequence["response"])) {
                    doc.getElementById("phppot-message").innerHTML = consequence["response"];
                    doc.getElementById("phppot-message").setAttribute("class", consequence["responseType"]);
                } else {
                    doc.getElementById("phppot-message").innerHTML = "Invalid JSON format.";
                    doc.getElementById("phppot-message").setAttribute("class", "error");
                }
            }
        }
        ajax.open("POST", "venture path/json-post-php/example2/ep.php");
        ajax.setRequestHeader("Content material-Sort", "utility/json;charset=UTF-8");
        ajax.ship(jsonstring);
    }
</script>

<physique>
    <div class="phppot-container">
        <h1>Obtain JSON POST in PHP</h1>
        <kind motion="" methodology="submit" id="kind">
            <div id="phppot-message"></div>
            <div class="row">
                <label>Enter JSON knowledge</label>
                <textarea identify="json_input" class="full-width" rows="5" cols="50" id="json_string"> </textarea>
            </div>
            <div class="row"><enter kind="button" worth="Submit" id="btnsubmit" onclick="submitForm();"></div>
        </kind>
    </div>
</physique>

</html>

This operate reads the uncooked JSON knowledge from the request physique. It makes use of the PHP file_get_contents(‘php://enter’) and json_encode() to get the JSON string posted.

example3/ep.php

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

View demo Obtain

↑ Again to High

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments