By using this site you agree to the use of cookies and related technologies.

Learn more

HTTP Post Requests with cURL in PHP

cURL tutorial showing how to create http post request from PHP.

Edited: 2016-10-05 03:47

Performing a HTTP POST Request with cURL can be somewhat complicated, because a lot of unexpected things might happen, in the light of this, it seems more streight forward to use file_get_contents – anyway, lets get started!

The important parts when making a post request, is the CURLOPT_POST and CURLOPT_POSTFIELDS – the below script should be fully working.

$url = "http://beamtic.com/Examples/http-post.php"; // The POST URL
// The POST Data
$postdata  = "name=Jacob";
$postdata .= "&bench=150";

$ch = curl_init($url);

// Set the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// Pass the post parameters as a naked string
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

// Option to Return the Result, rather than just true/false
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Perform the request, and save content to $result
$result = curl_exec($ch);

// Show the result?
echo $result;

As mentioned ealier, the important part in the above script is the part where you set the request-type to POST, and pass the data to be posted. I.e.

// Set the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// Pass the post parameters as a naked string
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

The variable $postdata contains a string, where each parameter is separated by unencoded ampersands. To easily add and remove parameters in a very read-able way, you can do like we did in this script. I.e

// The POST Data
$postdata  = "name=Jacob";
$postdata .= "&bench=150";

This is just as clean and readable as using an array.

Problems with cURL and POST Requests

To begin with, cURL in PHP seems to be poorly documented, but this Tutorial hopefully clears that up a bit.

One problem you may encounter while using cURL, is that its sending the POST as multipart/form-data with a boundary, instead of sending it as application/x-www-form-urlencoded. The reason this is happening, is that cURL for some reason does this if you pass the post parameters as an array.

We have been unable to get this to work properly – even when setting headers manually and using http_build_query on the array – maybe its character-dependent? In any case, there is no reason to use an Array. Using an Array seems even more messy than just passing the data as a naked-untreated string.