Re: cURL oddities
Posted by:
toivo
(203.19.130.---)
Date: June 25, 2008 01:30AM
Hi,
Here is an example from a working application:
// may not be needed
$user_agent = ' Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12';
$form_vars = array();
$form_vars['FirstName'] = $first_name;
$form_vars['LastName'] = $last_name;
$form_vars['Company'] = $company;
$form_vars['Country'] = $country;
$form_vars['Email'] = $email;
$post_data = '';
foreach ($form_vars as $var => $value) {
if (trim($value)) {
$post_data .= urlencode($var).'='.urlencode($value).'&';
}
}
// drop last &
$post_data = substr($post_data, 0, -1);
// get curl handle
$ch = curl_init();
if ($ch === false) {
error_log('Unable to get a curl handle');
}
curl_setopt($ch, CURLOPT_URL, $my_url);
curl_setopt($ch, CURLOPT_REFERER, 'http://example.com');
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); // may not be needed
curl_setopt($ch, CURLOPT_POST, 1); // POST
curl_setopt($ch, CURLOPT_HEADER, 0); // do not return headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // causes an error in eval()
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // contents of POST
$curl_result = @curl_exec($ch);
$errnum = curl_errno($ch);
if ($errnum != 0) {
$curl_error = curl_error($ch);
error_log($my_url." status: ".$errnum." - ".$curl_error);
}
curl_close($ch);
A couple of tips:
If your request needs to go through a proxy, you need to include the details:
curl_setopt($ch, CURLOPT_PROXY, '192.168.2.99'); // proxy
curl_setopt($ch, CURLOPT_PROXYPORT, 3128); // proxy port
I noticed that if the code is run through eval(), this change wouldmake it work:
//$set_transfer = CURLOPT_RETURNTRANSFER; // constant causes error in curl_setopt
$set_transfer = 19913;
curl_setopt($ch, $set_transfer, 1); // transfer the return as string
Regards,
toivo
Sydney, Australia