【问题标题】:Rewriting some code using fsockopen to use curl instead使用 fsockopen 重写一些代码以使用 curl 代替
【发布时间】:2011-06-18 05:57:52
【问题描述】:

我的主机不允许 fsockopen,但它允许 curl。我很高兴使用 cli 中的 curl,但不必在 PHP 中使用太多。我如何改用 curl 来写这个?

$xmlrpcReq 和 Length 在前面定义。

$host = "http://rpc.pingomatic.com/";
$path = "";

$httpReq  = "POST /" . $path . " HTTP/1.0\r\n";
$httpReq .= "User-Agent: My Lovely CMS\r\n";
$httpReq .= "Host: " . $host . "\r\n";
$httpReq .= "Content-Type: text/xml\r\n";
$httpReq .= "Content-length: $xmlrpcLength\r\n\r\n";
$httpReq .= "$xmlrpcReq\r\n";   

if ($pinghandle = fsockopen($host, 80)) {
    fputs($pinghandle, $httpReq);
    while (!feof($pinghandle)) { 
        $pingresponse = fgets($pinghandle, 128);
    }
    fclose($pinghandle);
}

非常感谢!

【问题讨论】:

  • 你怎么知道你的主机不允许 fsockopen?托管商这样做并不常见,因为它禁用了所有漂亮的 http 库(= 不是 curl)。您收到了哪条错误消息? (否则我会假设错误源自无效的 Host: 标头。)
  • 是的,我已经与主机确认不允许使用 fsockopen。垃圾!

标签: php curl fsockopen fclose fputs


【解决方案1】:

试试这个:

$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'My Lovely CMS');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlrpcReq);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($curl, CURLOPT_URL, "http://rpc.pingomatic.com/");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$pingresponse = curl_exec($curl);

【讨论】:

  • 尚未完全测试,但从外观上看,这基本上是正确的。我发现我每次都必须将 $curl 作为第一个参数传递给 curl_setopt,并添加一个 CURLOPT_URL 行以使其工作,但看起来它会工作 - 谢谢!
猜你喜欢
  • 2014-11-25
  • 2018-07-02
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 2011-05-24
  • 2016-04-17
  • 2012-06-08
  • 2014-08-20
相关资源
最近更新 更多