PHP cURL vs file_get_contents

访问REST API时,这两段代码有什么不同?

$result = file_get_contents('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url'); 

 $ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); 

他们两人产生同样的结果,由此判断

 print_r(json_decode($result)) 

file_get_contents()是一个简单的螺丝刀。 非常适合简单的GET请求,其中头部,HTTP请求方法,超时,cookiejar,redirect和其他重要的东西都不重要。

带有stream上下文的 fopen()或者带有setopt的 cURL是你可以想到的每个位和选项的动力。

除此之外,由于一些最近的网站黑客,我们不得不保护我们的网站更多。 在这样做的时候,我们发现file_get_contents失败了, curl仍然可以工作。

不是100%,但我相信这个php.ini设置可能已经阻止了file_get_contents请求。

 ; Disable allow_url_fopen for security reasons allow_url_fopen = 0 

无论哪种方式,我们的代码现在与curl

这是旧的主题,但在我的最后一个testing我的API,curl更快,更稳定。 有时候,如果cURL只需要1.4到1.9秒,那么更大请求上的file_get_contents就需要5秒以上,而且速度要快一倍。

我需要添加一个注释,我只发送GET和recive JSON内容。 如果你正确设置curl,你会得到很好的回应。 只是“告诉”要卷起你需要发送什么,你需要收回什么,就是这样。

在您的检查中,我想要做这个设置:

 $ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); $result = curl_exec($ch); 

此请求将返回0.01秒内的数据