Submitting a POST HTTP Request with cURL

Thursday, February 26, 2009

This may happen when in the middle of a PHP script you need to send data to another server and retrieve the response. This case is often when dealing with a third-party vendor, such as a payment company, data provider, and so on. 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.

Note
It is also possible to handle POST arguments via directly connecting to the server with sockets or an fopen() command and sending the POST data manually.

The following code shows a function that handles doing a POST for you, just by passing it the URL to contact, as well as the POST data. The POST data should be in the same format that http_build_query() produces, and therefore, we will make sure to use it.

<?php
// Create a function to handle the posting of data
function http_post($url, $post) {
 $c = curl_init();
 curl_setopt($c, CURLOPT_URL, $url);

 curl_setopt($c, CURLOPT_POST, true);
 curl_setopt($c, CURLOPT_POSTFIELDS, $post);

 curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
 return curl_exec($c);
}
$fields = array('data' => 'John Doe', 'idx' => 11321);

echo http_post('http://example.com/script.php', http_build_query($fields));
?>


cURL can handle many advanced Internet protocols and is extremely powerful. This is just a small taste of what it can do. To discover more, read the documentation at http://php.net/curl.

Note
cURL support in PHP relies on the libcurl library, which must be obtained and compiled into PHP, as well as enabling the extension, which does not exist by default either. More information on how to accomplish these tasks is available in the PHP documentation at http://php.net/curl.

0 comments: