When curl is refusing to work as you expect…

Reading Time: < 1 minute

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

Problem:

[php]
$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);
[/php]

was returning an empty string, while

[php]
$result = file_get_contents($url);
[/php]

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.

[php]
$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);
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy

This site uses Akismet to reduce spam. Learn how your comment data is processed.