Using proxy with authentication in PHP reCAPTCHA

When using PHP reCAPTCHA, you need to modify the _recaptcha_http_post method to use a proxy with username and password as per below.

Thanks to Eli Fulkerson's blog post, Recaptcha via proxy server that showed me how to add proxy support. Thanks to lcollet on this Drupal code page for the clues to add username and password.

function _recaptcha_http_post($host, $path, $data, $port = 80) {

   $proxy_host = 'PROXY-HOST';
   $proxy_port=PROXY-PORT;
   $proxy_username='PROXY-USERNAME';
   $proxy_password='PROXY-PASSWORD';

   $req = _recaptcha_qsencode ($data);

   $http_request  = "POST http://$host$path HTTP/1.0\r\n";
   $http_request .= "Host: $host\r\n";
   $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
   $http_request .= "Content-Length: " . strlen($req) . "\r\n";
   $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";

   if (!empty($proxy_username)) {
      $auth_string = base64_encode($proxy_username . ($proxy_password != '' ? ":{$proxy_password}" : ''));
      $http_request .= "Connection: close\r\n";
      if ( !empty($auth_string ) ) $http_request .= "Proxy-Authorization: Basic {$auth_string}\r\n";
   }

   $http_request .= "\r\n";
   $http_request .= $req;

   $response = '';
   if( false == ( $fs = @fsockopen($proxy_host, $proxy_port, $errno, $errstr, 10) ) ) {
      die ('Could not open socket');
   }

   fwrite($fs, $http_request);

   while ( !feof($fs) )
      $response .= fgets($fs, 1160); // One TCP-IP packet
   fclose($fs);
   $response = explode("\r\n\r\n", $response, 2);

   return $response;
}

Popular Posts