How to execute an HTTP POST using PHP cURL

Josh Sherman
1 min read
Software Development PHP

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 = '';

// 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles