Skip to content
PHP Logo

How can one effectively use cURL in PHP for sending data to an external API?

To effectively use cURL in PHP for sending data to an external API, you can create a cURL handle, set the necessary options such as the API endpoint, method, headers, and data to be sent, execute the cURL request, and then handle the response accordingly.

php
// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/endpoint');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['key' => 'value']));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);

// Execute cURL request
$response = curl_exec($ch);

// Check for errors and handle response
if($response === false){
    echo 'cURL error: ' . curl_error($ch);
} else {
    echo 'Response: ' . $response;
}

// Close cURL session
curl_close($ch);