Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Alternative for file_get_contents() using curl
<?php
// http://25labs.com/alternative-for-file_get_contents-using-curl/
function file_get_contents_curl($url, $retries=5)
{
$ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36';
if (extension_loaded('curl') === true)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // The number of seconds to wait while trying to connect.
curl_setopt($ch, CURLOPT_USERAGENT, $ua); // The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($ch, CURLOPT_FAILONERROR, TRUE); // To fail silently if the HTTP code returned is greater than or equal to 400.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); // To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // The maximum number of seconds to allow cURL functions to execute.
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // The maximum number of redirects
$result = curl_exec($ch);
curl_close($ch);
}
else
{
$result = file_get_contents($url);
}
if (empty($result) === true)
{
$result = false;
if ($retries >= 1)
{
sleep(1);
return file_get_contents_curl($url, --$retries);
}
}
return $result;
}
?>
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Oct 22, 2013

Using $retries-- causes it to run until a successful download (regardless of the number of attempts) because the value pre-increment is passed (always 5, or whatever is passed to the function). It should use --$retries instead.

@sitthykun

This comment has been minimized.

Copy link

@sitthykun sitthykun commented Jul 1, 2014

It is a great idea

@bb2ebb

This comment has been minimized.

Copy link

@bb2ebb bb2ebb commented Jul 30, 2017

great solution guys, I love you so much ;)

@kiyeon

This comment has been minimized.

Copy link

@kiyeon kiyeon commented Mar 10, 2018

awesome!

@delowar-hosain

This comment has been minimized.

Copy link

@delowar-hosain delowar-hosain commented Dec 27, 2018

Working.... Thank You!

@benocd

This comment has been minimized.

Copy link

@benocd benocd commented Apr 16, 2019

Works like a charm. Thanks a lot ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment