Curl PHP POST Example

Using API’s is essential in any developers life and I like to keep things simple where I can so using a PHP curl request is great for me. I use this code in everyday development life and I’m hoping it help someone else.

Requirements:

URL endpoint (url address from where you are requesting data)

Content-Type (what format of data are you requesting)

Your Good To Go

In a new php file you will need the following code (I will explain what variables go where soon)

	$headers = array(
	      'Host: accounts.google.com',
	      'Content-Type: application/x-www-form-urlencoded'
	);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url );
	//curl_setopt($ch, CURLOPT_HEADER, TRUE );
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
	curl_setopt($ch, CURLOPT_POST, count($fields));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$result = curl_exec($ch);
	curl_close($ch);

First you will have to create the headers variable with the content type and host url (this will be provided by the API host)

I have commented out the header function this will bring back the HTTP headers with the request (great for debugging)

In the CURLOPT_POST I count how many fields I am posting into the API (this is not essential)

Then ing the CURLOPT_POSTFIELDS you will add the data you wish to send in the format requested for the API.

Now $result will have the data sent back from the API.

Remember is you get errors try showing the HTTP headers as it could be a simple case of wrong url (I have done that many times)

I will be posting examples of GET and PUT curl request soon. 🙂