How to Post JSON Data with PHP cURL & Receive

In this tutorial i will show you how to post json data with php curl and receive the raw json sent. You can simply use PHP file_get_contents() to send HTTP GET request. But it’s not the same case with HTTP POST. Fortunately PHP cURL makes the process very simple. You may also like Lusha API using PHP curl and How to Subscribe to List using MailChimp API using PHP.

The following is the PHP code to send json through POST request.

<?php
    $url = 'http://mydomain.com/api/emp/create';

    $data = array(
        'site' => 'mydomain.com',
        'account' => 'admin',
        'status' => 'true'
    );
    $json = json_encode($data);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    echo $result;
?>

Below is the code to receive the json posted

<?php
    $output = file_get_contents("php://input");
    echo $output;
?>

Leave a Reply

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