I’ve been doing a lot of API integration recently and cURL ends up being exceptionally handy when you are POSTing to an endpoint. Fortunately using cURL in PHP is really easy:

// Sets our destination URL
$endpoint_url = 'https://somesite.com/path/to/endpoint';

// Creates our data array that we want to post to the endpoint
$data_to_post = [
	'field1' => 'foo',
	'field2' => 'bar',
	'field3' => 'spam',
	'field4' => 'eggs',

// Sets our options array so we can assign them all at once
$options = [
  	CURLOPT_URL        => $endpoint_url,
	CURLOPT_POST       => true,
	CURLOPT_POSTFIELDS => $data_to_post,

// Initiates the cURL object
$curl = curl_init();

// Assigns our options
curl_setopt_array($curl, $options);

// Executes the cURL POST
$results = curl_exec($curl);

// Be kind, tidy up!

Really not much to it. Often times you’ll find yourself fighting with the cURL options a bit to find that secret sauce. Some endpoints require that the correct headers are set and will bark until they are set up correctly, other than that, cURL is pretty painless to use.

Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: