How to execute an HTTP POST using PHP cURL

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!
curl_close($curl

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.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.