Recaptcha using CURL

4,259 views
Skip to first unread message

SAmark

unread,
Sep 7, 2009, 3:48:06 AM9/7/09
to reCAPTCHA
Hi,
I had to resort to using CURL for recaptcha as fsockopen is disabled
on the server and theres no way around this for now.

I implemented the code but Im not getting the desired result. Im
getting returned a 400 Bad Request error. Below is my code:


$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $host);
curl_setopt ($ch, CURLOPT_PORT, $port);
curl_setopt ($ch, CURLOPT_TIMEOUT, 10);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt ($ch, CURLOPT_HTTPHEADER, $http_request);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
$fs = curl_exec($ch);

Im new to CURL so I cant say im too confident with the above code so
If anyone can give me an idea of what the problem is that would be
great.

Thanks
Mark

mbirth

unread,
Sep 8, 2009, 4:33:25 AM9/8/09
to reCAPTCHA
I had to use cURL because we use a HTTP proxy for outbound connections
and fsockopen() tried to connect directly. This seems to work:

/**
* Submits an HTTP POST to a reCAPTCHA server
* @param string $host
* @param string $path
* @param array $data
* @param int port
* @return array response
*/
function _recaptcha_http_post($host, $path, $data, $port = 80) {
$add_headers = array(
"Host: $host",
);

$curl = curl_init( 'http://' . $host . ':' . $port . $path );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt( $curl, CURLOPT_HTTP_VERSION,
CURL_HTTP_VERSION_1_0 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'reCAPTCHA/PHP' );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
curl_setopt( $curl, CURLOPT_HEADER, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $add_headers );
if ( isset( $_ENV['http_proxy'] ) && !empty ( $_ENV
['http_proxy'] ) ) {
curl_setopt( $curl, CURLOPT_HTTPPROXYTUNNEL, true );
curl_setopt( $curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
curl_setopt( $curl, CURLOPT_PROXY, $_ENV
['http_proxy'] ); // CURLOPT_PROXYUSERPWD as username:password
needed?
}

$response = curl_exec( $curl );
if ( $response === false ) die('Error connecting to ' .
$host . '.');

$response = explode("\r\n\r\n", $response, 2);

return $response;
}

Cheers,
-mARKUS

SAmark

unread,
Sep 9, 2009, 8:41:06 AM9/9/09
to reCAPTCHA
Thanks markus, that worked perfectly!
Message has been deleted

John Williams

unread,
Aug 27, 2014, 4:14:36 PM8/27/14
to reca...@googlegroups.com, mbi...@googlemail.com
Thanks mARKUS! It does work!
Reply all
Reply to author
Forward
0 new messages