Send JSON Payload with PHP cURL and why there is no excuse to avoid becoming a better human being every day!

Hello, so I needed to send some JSON payloads from PHP to a remote server, and capture the response, also on JSON format (hello to my fellow JSON pushers out there!)

Well, it is natural to use the tried and true cURL extension for this, so here we go:

Prerequisites

  • You have a dev environment with PHP +8.x working right now (cli and web).
  • You have the cURL extension loaded on you php.ini (and it is working obviously)
  • You have hobbies apart from work and try to interact with other human beings in the real world.

The server

So, lets create a dummy server that will receive a JSON payload and reply with a message also JSON formatted.

WARNING: you may not like my programming style but you may enjoy it.

create a folder on your web server root named "test", inside create a file named "jsonecho.php" and copy the following code:

<?php

$response = array();
$response["errors"] = array();
$response["result"] = array();

try {

    $payload = json_decode(file_get_contents("php://input"), true);

    if (empty($payload["data"])) {
        throw new Exception("Error: I need a 'data' entry on the request payload to do my thing, ya dig!");
    }

    $response["result"]["msg"] = "Thank you, your data has been received.";
    $response["result"]["yourdata"] = $payload;
} catch (\Throwable $th) {

    $response["errors"][] = $th->getMessage();
} finally {

    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
}

What the script does is to receive a request and check if it contains a JSON object with a "data" entry. If there is one, it will send a response with a thank you message and return the information to the client.

Check if it works, just open your browser and go to http://localhost/test/jsonecho.php or whatever URL is correct on your current digital, PC, Server universe at that moment, it will show a message like this:

image.png

If that is the case, you are now a JSON server, REST API expert, great!

Now to the client, here comes cURL:

create another file "client.php" and copy the following code:

<?php

try {

    //data to be sent to the server. It is an array then it is converted to json with json_encode()
    $payload = array("data" => "My data");
    //service URL, it is self-explanatory i guess. (where the data is going to be sent).
    $requestUrl = "http://localhost/test/jsonecho.php";

    //some messages to keep our user in a calm, chilled state of mind, with good vibes
    echo "Sending payload to " . $requestUrl . PHP_EOL;
    echo "Payload Content:" . PHP_EOL;
    print_r($payload);
    echo PHP_EOL;

    //cURL init, a mandatory sentence that can't be avoided, just enjoy.
    $curl = curl_init();

    //we use the curl_setopt() to... set... curl... opt...ions
    //Set the remote service URL
    curl_setopt($curl, CURLOPT_URL, $requestUrl);
    //set curl to POST mode
    curl_setopt($curl, CURLOPT_POST, true);
    //set the HTTP headers that you want to send with your request, array(), in this particuar case we tell the server that there will be JSON involved.
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/json", "Content-Type:application/json"));
    //set the data to be posted to the remote URL, json_encoded and JSON_UNESCAPED_UNICODE because i like my coffe black and my unicode unescaped.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE));
    //very important!, this tells curl to return the result data from the server when curl_exc() is called and not to print it to the output (default)
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    //curl... exec... ute what i tell you to!
    $resp = curl_exec($curl);
    //check the HTTP status, very important for error validation and boring stuff like that.
    $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    //show any errors reported by cURL.
    echo curl_error($curl) . PHP_EOL;
    //Aaaand the end. Close the connection.
    curl_close($curl);

    //transform the string received from JSON format to array, you may want to use objects instead of arrays, just use false on the second param or don't use it.
    $response = json_decode($resp, true);

    //now we show the result:
    echo "Response HTTP STATUS: " . $httpStatus . PHP_EOL;
    echo "Response received:" . PHP_EOL;
    print_r($response);
    echo PHP_EOL;
} catch (\Throwable $th) {
    //error handling...
    echo "There was an error:" . PHP_EOL;
    echo $th->getMessage() . PHP_EOL;
}

Guess the comments are self-explanatory so lets move on, if you want to learn more about cURL options check the docs

Now, to the CLI!, just go to the folder where the client.php is located and execute the script:

image.png

The output will be something like this:

image.png

Ooohh, and remember: there is no excuse to avoid becoming a better human being every day!

Vires acquirit eundo!