The PHP cURL is a library used for making HTTP requests. In order to use PHP cURL, you must have installed and enabled libcurl module for PHP on your system. In this tutorial, you will learn how to POST JSON data with PHP cURL requests. Basically, there are 4 steps involved to complete a cURL request using PHP.
- curl_init — The first step is to initializes a new session of cURL and return a cURL handle to other functions.
- curl_setopt — The second step is to set options for a cURL session handle. All these settings are very well explained at curl_setopt().
- curl_exec — In third step it perform a cURL session based on above options set.
- curl_close — The last step is to close a cURL session initialize by curl_init() and free all resources. Also deleted the cURL handle.
Let’s use the below sample code to create a POST request with PHP cURL.
// Data in JSON format
$data = array(
'username' => 'tecadmin',
'password' => '012345678'
$payload = json_encode($data);
// Prepare new cURL resource
$ch = curl_init('https://api.example.com/api/1.0/user/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Length: ' . strlen($payload))
// Submit the POST request
$result = curl_exec($ch);
// Close cURL session handle
The main thing is that the request must be a POST request with properly json-encoded data in the body. The headers must properly describe the post body.