Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is blocking fsockopen?

After struggling for half a day, I finally manage to get reCAPTCHA to work by converting this function:

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

 $req = _recaptcha_qsencode ($data);

 $http_request  = "POST $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";
 $http_request .= "\r\n";
 $http_request .= $req;

 $response = "";
 if( false == ( $fs = @fsockopen($host, $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;
}

to:

function _recaptcha_http_post($host, $path, $data, $port = 80) {
 $req = _recaptcha_qsencode ($data);
 $request = curl_init("http://".$host.$path);

 curl_setopt($request, CURLOPT_USERAGENT, "reCAPTCHA/PHP");
 curl_setopt($request, CURLOPT_POST, true);
 curl_setopt($request, CURLOPT_POSTFIELDS, $req);
 curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

 $response = curl_exec($request);
 return $response;
}

Basically, I am interested to find out why curl works while fsockopen fails with "Could not open socket". Thanks.

In addition: Sockets Support is enabled.

like image 809
Question Overflow Avatar asked May 06 '12 15:05

Question Overflow


People also ask

What is Fsockopen?

The fsockopen() function opens an Internet or Unix domain socket connection.

How do I check Fsockopen?

This sample code checks to see if the fsockopen() function is available. To check for another function, change the $function_name variable's value: <? php $function_name = "fsockopen"; if ( function_exists($function_name ) ) { echo "$function_name is enabled"; } else { echo "$function_name is not enabled"; } ?>

Is similar to Fsockopen () in PHP?

The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.


1 Answers

I might be wrong, but you use $port = 80 in fsockopen() while in cURL case this variable is not used at all. I had same problem when tried to connect to SSL via port 80 instead of port 443; as far as I know, cURL checks SSL by default and connects accordingly.

Also, try running cURL with CURLOPT_VERBOSE to see what it does.

like image 178
Damaged Organic Avatar answered Sep 29 '22 12:09

Damaged Organic