To make an HTTP POST request with cURL in PHP, you can use the following code:
// Create a new cURL resource
$ch = curl_init();
// Set the URL and other options
curl_setopt($ch, CURLOPT_URL, "http://example.com/api");
curl_setopt($ch, CURLOPT_POST, true);
// Set the POST data
$postData = array(
'param1' => 'value1',
'param2' => 'value2'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// Execute the request
$response = curl_exec($ch);
// Close cURL resource
curl_close($ch);
// Handle the response
if ($response === false) {
// Request failed
echo curl_error($ch);
} else {
// Request succeeded
echo $response;
}
In this code, you first create a new cURL resource using curl_init()
. Then, you set the URL you want to send the request to using curl_setopt()
. Additionally, you set the CURLOPT_POST
option to true
to indicate that it's a POST request.
Next, you set the POST data using curl_setopt()
. The data can be passed as an array, which will be serialized by cURL.
After setting all the options, you execute the request with curl_exec()
, which will send the request and return the response. Finally, you close the cURL resource with curl_close()
.
You can then handle the response as needed. If the request fails, you can use curl_error()
to get the error message. Otherwise, you can process the response as necessary.