howtos » curl
cURL is used to interact with remote URLs without needing a user to initiate the process (e.g. by clicking on a form submit button). cURL is useful for submitting HTTP POST/PUT/DELETE requests when dealing with web services. PHP has inbuilt cURL support since PHP 4.0.2 using cURL's libcurl library. Find out more about PHP/CURL -- using libcurl with PHP here.
A fullset of cURL options and what they mean can be found in
PHP's manual entry for curl_setopt().
PHP:
-
//Contains encoded string to pass along for basic authentication purposes
-
-
//Target URL - the URL you want to submit a form to
-
$target_url = 'http://www.remotesite.com/post_target.php';
-
-
//Create a new cURL handle
-
//Passing the target URL to curl_init allows you to bypass the call curl_setopt($ch, CURLOPT_URL, $target_url);
-
$ch = curl_init($target_url);
-
-
//Tell the handler that the info is to be sent using an HTTP POST request
-
curl_setopt($ch, CURLOPT_POST, true);
-
-
//Set other relevant headers. Place each header as an array element
-
//An alternative to building the Authorization header is to use curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
-
'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3');
-
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
-
//Pass the POST fields - be sure to urlencode your value strings (hint: http_build_query() will do this for you; PHP5)
-
//Below we assume values have already been posted to this script and kept in $_POST. We have validated the submission and
-
// are now posting the same values to a remote URL
-
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
-
-
//When we execute the handle, we want curl_exec() to return to a string rather than directly outputting it
-
curl_setopt($ch, CURLOPT_RETURNTRANSER, true);
-
-
//Don't use a cached connection - explicitly create a new one
-
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
-
-
//Fail if cannot connect to the target server within 5 seconds
-
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
-
-
//If the target server returns a redirect request using the "Location:" header directive, then follow it.
-
//To prevent recursive redirects, only do a max of 5 follows
-
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
-
-
//Let's now execute the handler
-
//Because CURLOPT_RETURNTRANSFER is true, we need to capture the return value of curl_exec()
-
$response_data = curl_exec($ch);
-
-
//Was there an error?
-
//curl_errno() returns the error code
-
//curl_error() returns a clear text message for the last cURL operation
-
if (curl_errno($ch)> 0){
-
} else {
-
//Close the handler and release resources
-
curl_close($ch);
-
}
-
-
-
//Now do something with your data
-
return myProcessingFunction($data);