JSON is the most popular data format for exchanging data between a browser and a server. The JSON data format is mostly used in web services to interchange data through API. When you working with web services and APIs, sending JSON data via POST request is the most required functionality. PHP cURL makes it easy to POST JSON data to URL. In this tutorial, we will show you how to POST JSON data using PHP cURL and get JSON data in PHP.

Send JSON data via POST with PHP cURL

The following example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.

  • Specify the URL ($url) where the JSON data to be sent.
  • Initiate new cURL resource using curl_init().
  • Setup data in PHP array and encode into a JSON string using json_encode().
  • Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.
  • Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
  • Return response as a string instead of outputting it using the CURLOPT_RETURNTRANSFER option.
  • Finally, the curl_exec() function is used to execute the POST request.
// API URL
$url 'http://www.example.com/api';// Create a new cURL resource
$ch curl_init($url);// Setup request to send json via POST
$data = array(
    
'username' => 'codexworld',
    
'password' => '123456'
);
$payload json_encode(array("user" => $data));// Attach encoded JSON string to the POST fields
curl_setopt($chCURLOPT_POSTFIELDS$payload);// Set the content type to application/json
curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type:application/json'));// Return response instead of outputting
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);// Execute the POST request
$result curl_exec($ch);// Close cURL resource
curl_close($ch);

Receive JSON POST Data using PHP

The following example shows how you can get or fetch the JSON POST data using PHP.

  • Use json_decode() function to decoded JSON data in PHP.
  • The file_get_contents() function is used to received data in a more readable format.
$data json_decode(file_get_contents('php://input'), true);

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

I was recently working on a project where I needed to integrate an external API using HTTP cURL requests. It was my first time doing this and I had a lot of problems figuring this out. I wrote this post so I can remember my cURL API calls for next time, and maybe it can help you as well. 

The API calls and functions I’m using in this post are all working examples on PHP -v 5.6.

PHP cURL Basics

cURL stands for ‘Client URL Library’ and it allows you to connect and communicate with different types of servers with many different types of protocols (HTTP, https, FTP, proxy, cookies, …). More info about how cURL actually works can be found in the official PHP documentation. This article will provide more in-depth examples for integrating your applications.

I’ve received a lot of responses on ‘how does cURL actually work’ and I get the feeling that people don’t know what’s going on in a cURL call. Before we start with the article and our cURL setup, I’ve added a simple example of a plain cURL request. The request will return the API response as a string.

// create & initialize a curl session
$curl = curl_init();

// set our url with curl_setopt()
curl_setopt($curl, CURLOPT_URL, "api.example.com");

// return the transfer as a string, also with setopt()
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// curl_exec() executes the started curl session
// $output contains the output string
$output = curl_exec($curl);

// close curl resource to free up system resources
// (deletes the variable made by curl_init)
curl_close($curl);

Note that we stored our curl_exec() in a variable $output. This $output variable is still available in our program even after we closed it with curl_close(). So after we did our call and closed the connection, we can still access the result using our $output variable.

Now that we understand the basics, let’s try to put this into a function we can reuse within our application.

PHP cURL setup

Implementing an external API into your project is probably going to take more than just one API call and from different pages in your project. This is why I’ve created a ‘simple’ PHP script that allows us to call this function, with a set of parameters, and a cURL request will be done.

Make sure to put this code into a file or place that can be accessed by your entire app or website. (I’ve updated this function so we’ll be able to define the headers when we’re making the call. I’ve added a section for custom headers at the bottom!)

function callAPI($method, $url, $data){
   $curl = curl_init();
   switch ($method){
      case "POST":
         curl_setopt($curl, CURLOPT_POST, 1);
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
         break;
      case "PUT":
         curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);			 					
         break;
      default:
         if ($data)
            $url = sprintf("%s?%s", $url, http_build_query($data));
   }
   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(
      'APIKEY: 111111111111111111111',
      'Content-Type: application/json',
   ));
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:
   $result = curl_exec($curl);
   if(!$result){die("Connection Failure");}
   curl_close($curl);
   return $result;
}

This is a basic setup for doing a cURL call and I’m using a switch statement to check if the API call will be a POST, PUT, or something else (get or delete). I’ll go deeper into the switch case while we’re doing the specific requests.

I’m using if-statements inside the switch-case to see if we want to provide JSON data into our call or not. For the POST and PUT request the if-statement is not really necessary because we’re only using POST or PUT with data, but it’s an extra security to make sure our call function won’t break.

PHP cURL GET request

The most simple API call is the GET call, so let’s start with that! Our callAPI function expects 3 parameters: $method, $url and $data. We need to give those parameters to all our API calls, so for a cURL GET, we can just set $data on false because we are not passing any data with a GET call.

$get_data = callAPI('GET', 'https://api.example.com/get_url/'.$user['User']['customer_id'], false);
$response = json_decode($get_data, true);
$errors = $response['response']['errors'];
$data = $response['response']['data'][0];

$get_data already returns all the data we want from the API in a json string. I’m using $response to convert the json string back to a usable PHP array. You can skip those steps if you want, this is my personal preference. I’m also using the extra $errors and $data arrays to store the actual data and errors.

PHP cURL POST request

Obviously, a POST request does require data. Make sure your json-data is correct, otherwise the request will keep returning errors. Although… If we receive errors from the API, that means our calls are working 😉

In my example I’m using the CakePHP syntax for setting up my json array, so don’t mind that.

$data_array =  array(
      "customer"        => $user['User']['customer_id'],
      "payment"         => array(
            "number"         => $this->request->data['account'],
            "routing"        => $this->request->data['routing'],
            "method"         => $this->request->data['method']
      ),
);
$make_call = callAPI('POST', 'https://api.example.com/post_url/', json_encode($data_array));
$response = json_decode($make_call, true);
$errors   = $response['response']['errors'];
$data     = $response['response']['data'][0];

Because we’re doing an API call with json data, I’m converting my PHP array to a json string with json_encode($data_array);. The response will come in as a json string again, so I’m using json_decode($make_call, true); to convert the json string back to a usable PHP array. Same as we did in our GET call, so you can skip these steps again if you don’t need them.

PHP cURL PUT request

The PUT request is almost the same as the POST request. I had a hard time figuring out how to pass data into a PUT call. If we take a look at our callAPI() function, you see that I changed some things up between the PUT and the POST request. We can still use the same parameters in our callAPI() function as always.

$data_array =  array(
   "amount" => (string)($lease['amount'] / $tenant_count)
);
$update_plan = callAPI('PUT', 'https://api.example.com/put_url/'.$lease['plan_id'], json_encode($data_array));
$response = json_decode($update_plan, true);
$errors = $response['response']['errors'];
$data = $response['response']['data'][0];

PHP cURL DELETE request

The delete request is very simple again. We can just hit the API url with the $id we want to remove and poof… it’s gone forever.

callAPI('DELETE', 'https://api.example.com/delete_url/' . $id, false);

In the beginning we defined our callAPI function with preset headers. But what if we, for some reason, need to change the headers a bit for another call? We don’t want to write a whole new callAPI function just to edit some headers. Therefore, here’s an option on how to make the preset headers flexible:

function callAPI($method, $url, $data, $headers = false){
   $curl = curl_init();
   switch ($method){
      ...
   }
   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
   if(!$headers){
       curl_setopt($curl, CURLOPT_HTTPHEADER, array(
          'APIKEY: 111111111111111111111',
          'Content-Type: application/json',
       ));
   }else{
       curl_setopt($curl, CURLOPT_HTTPHEADER, array(
          'APIKEY: 111111111111111111111',
          'Content-Type: application/json',
          $headers
       ));
   }
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   // EXECUTE:
   ...
}

There are 2 differences here from our first function. 1: We’ve added an extra parameter in our function to define if we want to use a custom header or not. I put it to $headers = false to give it a default value. Now we’re not required to enter our headers with every call.

The second change is the if-statement when we’re setting the API headers. If we didn’t give in any headers when we make the call, it’s going to use our default headers instead of crashing. Now we’re ready to add custom headers with our call!

In this example, I’m using search parameters to search for specific data before I’ll pull in all the data with the API. To make the search, I obviously need to be able to add my search query into my callAPI headers. Here’s my example:

$one_month_ago = date("Y-m-d", strtotime(date("Y-m-d", strtotime(date("Y-m-d"))) . "-1 month"));
$rent_header = 'Search: and[][created][greater]=' . $one_month_ago . '%and[][created][less]=' . date('Y-m-d') . '%';
//the actual call with custom search header
$make_call = callAPI('GET', 'https://api.example.com/get_url/', false, $rent_header);

This is just an example on how to add headers. My example is to get all rows where a rent was paid in the last 30 days. $one_month_ago is just a helper variable. The $rent_header is the actual header I want to add to my default headers. This needs to be a string!!

When you’ve set the header, you can just do a regular api call and add your new header at the end.

I didn’t need to use any other API call methods like patch or purge or anything like that. These you need to figure out yourself. If there’s some magic going on in this post I hope my examples can give you a better understanding.

I recently wrote a part 2 for this post, that will talk about generating an AUTH-key (utoken) before we make our calls. Make sure to check it out here as well!

How do you send a POST request on cURL?

You can send a POST request with Curl by explicitly specifying the POST method with the -X POST command line parameter or passing data to Curl using the -d or --data command line parameter.

What is content

Content-Type - Everything curl. Content-Type. POSTing with curl's -d option will make it include a default header that looks like Content-Type: application/x-www-form-urlencoded . That is what your typical browser will use for a plain POST. Many receivers of POST data do not care about or check the Content-Type header.

What is Curlopt_returntransfer in cURL?

Description ¶ curl_exec(CurlHandle $handle ): string|bool. Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.

What is Curlopt_postfields?

CURLOPT_POSTFIELDS. The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'.