122

How do these two pieces of code differ when accessing a REST API?

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

and

$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);

They both produce the same result, judging by

print_r(json_decode($result))
4
  • 3
    cURL is capable of much more than file_get_contents. That should be enough.
    – user849137
    Jun 16, 2012 at 16:00
  • 24
    FWIW there's little difference with regards to speed. I've just finished fetching 5,000 URLs and saving their HTML to files (about 200k per file). I did half with curl and half with file_get_contents as an experiment and there was no discernible difference. Jun 17, 2013 at 22:36
  • 8
    It is possible to send post data with file_get_contents, as long as you are using a version that supports stream context. Dec 29, 2014 at 20:42
  • I prefer file_get_contents because of its simplicity, but I'm frequently unable to use it if allow_url_fopen is turned off in server configurations that I have no control over. So for that reason alone I recommend cURL with a possible function_exists('curl_init') check and if that doesn't pass a fallback to file_get_contents.
    – PHP Guru
    Apr 3 at 17:58

4 Answers 4

143

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

fopen() with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.

4
  • 18
    To stay within that metaphor, note that cURL is a powerdrill with a complicated drill chuck that requires you to know it pretty well to actually change it (read: setting cURL options is a bit tedious, but allows for doing anything you want).
    – poke
    Jun 16, 2012 at 16:09
  • 24
    file_get_contents allows also to set the context, which means you can set the header fields as you like.
    – velop
    Nov 3, 2013 at 14:36
  • 6
    and as addition to @velop's comment, through the stream context it is also possible to send POST, PUT, authentication, headers, content, proxy, and much more with one file_get_contents request Jul 29, 2015 at 14:53
  • 1
    @velop: Yes. And method, too. And redirects. And timeout... php.net/manual/en/context.http.php
    – Sz.
    Mar 28, 2018 at 19:54
30

In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.

Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.

; Disable allow_url_fopen for security reasons
allow_url_fopen = 0

Either way, our code now works with curl.

8
  • 9
    Yes, file_get_contents requires allow_url_fopen to be truthy.
    – Costa
    Nov 19, 2013 at 1:40
  • 2
    Yes, many hosting companies are disabling file_get_contents() due to many exploits that are known to use the function. cURL is the function people should be using in code now. Dec 20, 2013 at 4:43
  • 15
    @frustratedtech What "exploits" are these?
    – user895378
    Mar 2, 2014 at 15:36
  • 3
    Hosting companies disable allow_url_fopen because they kind of mistake it for allow_url_include. allow_url_fopen and file_get_contents are fine to use.
    – fritzmg
    May 4, 2015 at 10:42
  • 3
    @vr_driver those links have nothing to do with file_get_contents()
    – user895378
    Jun 24, 2015 at 15:16
27

This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.

On your exampe I would like to do this setup:

$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);

This request will return data in 0.10 second max

5
  • 1
    0.1 MICROseconds (1/1,000 of a MILIseconds) ... I find that hard to believe. Oct 17, 2016 at 0:22
  • Yes. I have some responses in 0.02ms for example Twilio API phone number check. Is fast. Oct 17, 2016 at 5:33
  • 5
    0.02ms = 20 microseconds; you said 0.1 microseconds which can't be right.
    – Walf
    Nov 22, 2016 at 2:14
  • 2
    This is almost twice as fast compare to file_get_contents I just did some API calls to confirm. 0.8 seconds for file_get_contents & 0.49 seconds for curl (3 API calls)
    – Jsp
    Aug 5, 2018 at 17:14
  • 1
    You should use your own setup. Then your queries would go from 1.4-1.9s to 0.01s ;) Nov 10, 2018 at 21:54
3

I know it is an old topic but I believe this is really important. And now, there are a lot of differences more than 8 years ago. As we all know, Curl is 3rd part library.

Simple Comparison: Last version of Curl library has more than 170 different functions to be able to send proper request to APIs. There were only 70 functions 8 years ago. Fact: still under development.

That's why I wanted to put a new comment to this question.

What is file_get_contents()

file_get_contents() is a filesystem function in PHP that you can read contents from a file and make requests using GET and POST methods. You can add parameters to your request while you're using file_get_contents() function. You can see the sample below.

$data = http_build_query(
    array(
        'user_id'   => '558673',
        'user_name' => 'John Doe'
    )
);

$config = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    )
);

$context = stream_context_create($config);

$result = file_get_contents('https://google.com', false, $context);

What is curl()

Curl is open source third party library. You can reach the git repo from here. This function "simulates" HTTP requests and responses. This simulation allows you handling async HTTP requests and complex data transfers. In addition, Curl is suitable for performing cross-domain based FTP request. It can be used in various apps like data crawling from a website and proxy setup.

Let's check a CURL request syntax.

$url = API_ENDPOINT."/get_movies";
        
  $curl = curl_init();
         
  $params = array(
    'category' => $category,
    'limit' => $limit,
    'start' => $start,
    'order' => $order,
    'term' => $term
  );

  $params_string = http_build_query($params);

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_POST, TRUE);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $params_string);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  
  $data = curl_exec($curl);     
  curl_close($curl);

  echo json_decode($data,TRUE); //service returns json in this sample

Note: This is the basic sample of a curl request. You can add more parameter and options to the curl object using its functions like CURLOPT_HTTPHEADER, CURLOPT_SSL_VERIFYPEER. These kind of parameters all up to you and the service that you trying to use.

CURL vs file_get_contents()

  • CURL is able to handle complex HTML communications, but file_get_contents() is not.
  • CURL supports HTTP PUT, GET, POST but file_get_contents() supports simple HTTP GET and HTTP POST requests.
  • CURL supports caching and cookies but file_get_contents() doesn’t support caching, cookies, etc.
  • CURL is able to use HTTP, HTTPS, FTP, FTPS and more. file_get_contents() uses HTTP and HTTPS protocols for communications.
  • CURL can be used to read, update and delete files from server, but file_get_contents() only allows you to read a file.
  • CURL is more secure and faster than file_get_contents()
  • CURL is bit more complex to understand than file_get_contents().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.