How To POST JSON Data with PHP cURL

How to post json data with php curl

PHP and cURL are a match made in heaven as together they allow web developers access to system information outside of their own ecosystem. It's common to task want to POST (send data) to another place, i.e. an API service. One example of that might be adding a lead to a CRM system from your website. To do that you'll use an API and within the API it's now likely that's RESTful. That also means that the data sent will be sent as a JSON object. JSON is a predefined structure for storing data, and having this pre-defined syntax means that you know what you're sending can be successfully read by the other side, the API server. The easy way to do this is by sending an HTTP request with the JSON data in the body of that request. Whilst there are other ways, let's explore how you can send JSON data with PHP using the cURL library.

Create the JSON object of data

First, you need to create a JSON object of data, that you want to send to the server. You don't need to know the syntax of JSON because using PHP, we can use json_encode. This takes an array of data and converts it into a fully compliant JSON object.

$data = array(
 'name' => 'John Doe',
 'email' => '[email protected]'
);

$json_data = json_encode($data);

Send Request using the PHP cURL library

Next, we need to use PHP's cURL library to prep and send the real request, with our JSON data to a given location. As we're posting data, we'll ensure that the request type is a POST request. For each endpoint, the API server should have documentation for you to read in order to get the correct endpoint URLs and HTTP method type. For every JSON POST request, we need to ensure we always set the request location, and request type as POST, ensure the content type is of type JSON, and finally include our JSON object (data).

To do we'll use PHP's curl_* functions. First, you need to initiate the curl function using curl_init. Make sure you assign this to a variable as you will need it later.

$ch = curl_init();

Next, we need to tell PHP what cURL options we want to set. PHP does a really good job of setting the most common default options for us, which typically we can leave, but some we must define ourselves and/or override. The location (URL) of the cURL request is the first important step to successfully POSTing JSON data with PHP. Using the curl_setopt function we can pass our initiated curl object ($ch) as the first param, next tell PHP which option we're setting, and finally the value.

Here we're setting the CURLOPT_URL option to our API server.

curl_setopt($ch, CURLOPT_URL, 'https://api-server-example.com/leads');

Next, we're telling PHP that is a POST request with CURLOPT_POST as "true".

curl_setopt($ch, CURLOPT_POST, true);

Now we're passing our previously created JSON data to PHP cURL using CURLOPT_POSTFIELDS option.

curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

Finally, we set the HTTP header content type to "application/json". This is helpful and in most API cases a requirement of the server. This tells the server that the data we're POSTing is of type JSON. This is so the server doesn't have to assume what the data might be, as we're explicitly saying, it's JSON.

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

Now that we've set all our options, it's time to fire off the request. We use the curl_exec function for this, passing our pre-built $ch variable. The output of the request is saved into $result, which we can use in many different ways to determine the status of the request. Typically that involves an HTTP status code and/or a JSON returned object from the API server.

$result = curl_exec($ch);

Regardless of the result of the endpoint, we'll want to close off the connection and all associated resources with the cURL request to save memory and continue our PHP script execution. This is always good practice to do this and you'll want to close off the cURL request before processing the results information.

curl_close($ch);

An alternative way to create and send JSON data

Previously we built a JSON object from an array but we can instead take this directly from a JSON file itself. For that, we can use the file_get_contents function in PHP. This will read the file that we provide and copy its data out. In this case, it will put that data into the variable $data.

$data = file_get_contents("example.json");

Conclusion

Working with APIs and cURL is an easy task once familiar with the PHP cURL library. The library (that's built into PHP) offers a lot of powerful tools to help you send data outside of your application.

  • Set the URL to the location where you want to post your data
  • Tell PHP that you're making a POST request, not a GET request
  • Add the JSON data to the curl request
  • Try to remember to close the curl connection after use

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all