When curl is refusing to work as you expect...
This blog post is older than 4 years and may no longer be valid.
1 min read

When curl is refusing to work as you expect...


…you probably need to look at the many options curl offers. But let me start from the beginning.

Problem:

$curl = curl\_init();

$url = 'http://api.somewebsite.com/whatever'; 
curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl\_exec($curl);

was returning an empty string, while

$result = file\_get\_contents($url);

worked fine. Now I’m not the biggest fan of opening an URL using file_get_contents(), so I tried some of the many options and finally found the one that solved my problem.

$curl = curl\_init();

$url = 'http://api.somewebsite.com/whatever'; 
curl_setopt($curl, CURLOPT_URL, $url); // important option goes here...
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($curl, CURLOPT\_RETURNTRANSFER, 1);

$result = curl_exec($curl);