什么阻止fsockopen?

时间:2012-05-06 15:57:22

标签: php curl fsockopen

经过半天的努力,我终于设法通过转换这个功能让reCAPTCHA工作了:

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;
}

为:

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;
}

基本上,我有兴趣找出curlfsockopen失败并且“无法打开套接字”时的原因。感谢。

此外:已启用套接字支持。

4 个答案:

答案 0 :(得分:1)

我可能错了,但您在$port = 80使用fsockopen(),而在 cURL 情况下,根本不使用此变量。尝试通过port 80而不是端口443连接到 SSL 时遇到同样的问题;据我所知,cURL默认会检查 SSL ,并相应地进行连接。

另外,尝试使用 CURLOPT_VERBOSE 运行cURL以查看其功能。

答案 1 :(得分:0)

$ errno和$ errstr里面的内容if(false === ...)?那么,如果你改为

,它会输出什么
 if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
  die ("Could not open socket, error: " . $errstr);
 }

答案 2 :(得分:0)

Googling因为你的错误导致想知道你的/etc/resolv.conf是否可以被PHP读取。在bash中执行ls -lah /etc/resolv.conf以查看它是否可读。你会得到类似的东西:

myserver:~ myname$ ls -lah /ets/resolv.conf
lrwxr-xr-x  1 root  wheel    20B 16 mrt  2011 /etc/resolv.conf
       ^ if there is an 'r' here it is readable. if you have '-' here, it is not.

如果它不可读,请尝试使用bash:chmod 644 /etc/resolv.conf来使其可读。

答案 3 :(得分:-1)

哇,

  if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
  die ("Could not open socket");
 }

这肯定没有任何意义。尝试:

    $fs = fsockopen($host, $port, $errno, $errstr, 10); // @ ignores errors
 if(!$fs) die ("Could not open Socket");

Skype有时也会阻止80端口。