Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

file_get_contents or curl in php?

Which of file_get_contents or curl should be used in PHP to make an HTTP request?

If file_get_contents will do the job, is there any need to use curl? Using curl seems to need more lines.

eg:

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); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all cURL has a lot of options to set. You can really set any option you need to - many supported protocols, file-uploads, cookies, proxies and more.

file_get_contents() really just GETs or POSTs the file and has the result.

However: I tried some APIs and did some "benchmarking":

cURL was a lot faster than file_get_contents
Just try it with your terminal: 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'));

Averaged cURL was 3-10 times faster than file_get_contents in my case. The api.local responeded with a cached JSON file - about 600kb.

I don't think it was coincidence - But that you can't measure this accurately, because the network and the response times differ a lot, based on their current load / network speed / response times etc. (local networks won't change the effect - there will be load & traffic too)

But for certain use cases, it could also be that file_get_contents is actually quicker.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...