【问题标题】:file_get_contents or curl in php?php中的file_get_contents或curl?
【发布时间】:2012-10-11 20:55:13
【问题描述】:

在 PHP 中应该使用 file_get_contentscurl 中的哪一个来发出 HTTP 请求?

如果file_get_contents 可以完成这项工作,是否需要使用curl?使用curl 似乎需要更多的行。

例如:

卷曲:

$ch = curl_init('http://www.website.com/myfile.php'); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $content); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$output = curl_exec ($ch); 
curl_close ($ch); 

file_get_contents:

$output = file_get_contents('http://www.website.com/myfile.php'.$content); 

【问题讨论】:

  • curl 可以比 file_get_contents() 做更多的事情,但是如果您不需要它做的任何事情,那么请采用更简单的方法。
  • 我听说,使用 file_get_contents 有一些安全威胁,所以很少有服务器在 PHP 中禁用此功能。
  • @Dagon phpsec.org/projects/phpsecinfo/tests/allow_url_fopen.html 这是我第一次读到关于安全问题的地方。此外,cURL 似乎比 file_get_contents 快。这是一个关于相同的好帖子 -> stackoverflow.com/questions/555523/…
  • @Dagon 在我以前的工作中,我们的企业 PHP 包禁用了 allow_url_fopen,因此在抓取 Web 服务时我们不得不使用 cURL。不确定具体问题是什么,但使用 cURL,您可以执行诸如在帖子中传递登录信息之类的操作,并且比使用 file_get_contents 更灵活地处理返回的数据。
  • @teami 特定于 include() 和 require(),而不是 op 的 file_get_contents 问题

标签: php curl file-get-contents


【解决方案1】:

首先cURL 有很多选项可以设置。您真的可以设置任何您需要的选项 - 许多支持的协议、文件上传、cookie、代理等等。

file_get_contents() 实际上只是 GET 或 POST 文件并得到结果。

但是:我尝试了一些 API 并做了一些“基准测试”:

cURL 比 file_get_contents
快很多 用你的终端试试吧:time php curl.php

curl.php:

<?php 
$ch = curl_init();
$options = [
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL            => 'http://api.local/all'
];

curl_setopt_array($ch, $options);
$data = json_decode(curl_exec($ch));
curl_close($ch);

fgc.php

<?php 
$data = json_decode(file_get_contents('http://api.local/all'));

在我的例子中,平均 cURL 比 file_get_contents 快 3-10 倍。 api.local 响应缓存的 JSON 文件 - 大约 600kb。

我认为这不是巧合 - 但您无法准确衡量这一点,因为网络和响应时间差异很大,这取决于它们当前的负载/网络速度/响应时间等。(本地网络胜出'不要改变效果 - 也会有负载和流量)

但对于某些用例,file_get_contents 实际上也可能更快。

于是我构建了一个简单的函数:https://git.io/J6s9e

【讨论】:

    【解决方案2】:

    CurlFile_get_contents 快。我只是对此做了一些快速的基准测试。

    使用 file_get_contents 获取 google.com 耗时(以秒为单位):

    2.31319094 
    2.30374217
    2.21512604
    3.30553889
    2.30124092
    

    CURL 拍摄:

    0.68719101
    0.64675593
    0.64326 
    0.81983113
    0.63956594
    

    【讨论】:

    • 您发布的这些测试结果(以秒为单位)真的是您在您的测试中获得的结果吗?差异似乎有点大..您使用什么php版本?
    【解决方案3】:

    供您参考,curl 是否可以让您有更多选择并使用 GET/POST 方法和发送参数。

    file_get_contents 将有更少的选项供您获取/发布参数。

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-19
      • 2011-06-23
      • 2015-08-28
      • 2012-11-05
      • 2013-06-30
      • 2013-07-23
      • 2013-11-17
      • 1970-01-01
      相关资源
      最近更新 更多