how to Submitting a POST HTTP Request with cURL

asked Sep 13, 2013 in PHP by rajesh
edited Sep 12, 2013
0 votes

1 Answer

0 votes
Situations exist where you may need, in the middle of a PHP script, to send data to another server and retrieve the response. Accomplishing this is easy to do with GET strings because you can just generate the string needed by hand and call it via file_get_contents() as a URL. (Or even using http_build_query() to help you create your data request.)
However, the situation is not as simple when you need to do a POST. POST commands go to a regular URL, but the data is sent separately as part of the request headers. The regular PHP URL wrappers cannot handle this. Therefore it is easiest to use the PHP cURL extension, which allows for complex interactions with Internet protocols.
Using cURL for HTTP POST Operations
// Create a function to handle the posting of data
function http_post($url, $post) {
// Initialize a cURL session:
$c = curl_init();
// Set the URL that we are going to talk to:
curl_setopt($c, CURLOPT_URL, $url);
// Now tell cURL that we are doing a POST, and give it the data:
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $post);
// Tell cURL to return the output of the page, instead of echo'ing it:
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
// Now, execute the request, and return the data that we receive:
return curl_exec($c);
// Create some data that we want to send as a post:
$fields = array('data' => 'Jonathan Swift', 'idx' => 5783);
// Actually perform the post to a url:
echo http_post('', http_build_query($fields));
cURL support in PHP relies on the libcurl library. cURL can handle many advanced Internet protocols and is extremely powerful. 
answered Sep 13, 2013 by rajesh
edited Sep 12, 2013