PHP cURL vs file_get_contents

How do these two code snippets differ when accessing the 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); 

Both of them give the same result, judging by

 print_r(json_decode($result)) 
+80
php curl file-get-contents
Jun 16 '12 at 15:58
source share
3 answers

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 don't matter.

fopen() with a thread context or cURL with setopt are powerdrills with every bit and an option you might think of.

+94
Jun 16 '12 at 16:00
source share

In addition to this, due to recent site hackers, we had to protect our sites more. At the same time, we found that file_get_contents failed to work, where curl will still work.

Not 100%, but I believe that this php.ini parameter may have blocked the file_get_contents request.

 ; Disable allow_url_fopen for security reasons allow_url_fopen = 0 

In any case, our code now works with curl .

+18
Jan 07 '13 at 1:51
source share

This is an old topic, but in my last test on one of my APIs, cURL is faster and more stable. Sometimes file_get_contents for a larger request takes more than 5 seconds, when cURL only needs from 1.4 to 1.9 seconds, which is twice as fast.

I need to add one note to just send a GET and receive JSON content. If you configured cURL correctly, you will have a great answer. Just β€œtell” cURL what you need to send, and what you need to receive and what it is.

For your example, I would like to make this setting:

 $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 query will return data with a maximum value of 0.01 seconds.

+6
May 16 '16 at 14:12
source share



All Articles