PHP cURL vs file_get_contents

Salvador Dali picture Salvador Dali · Jun 16, 2012 · Viewed 107.1k times · Source

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

Answer

Xeoncross picture Xeoncross · Jun 16, 2012

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.