Skip to content

Instantly share code, notes, and snippets.

@jrivero
Last active February 21, 2024 11:30
Show Gist options
  • Save jrivero/5598138 to your computer and use it in GitHub Desktop.
Save jrivero/5598138 to your computer and use it in GitHub Desktop.
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;
}
?>
Copy link

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
Copy link

It is a great idea

@bb2ebb
Copy link

bb2ebb commented Jul 30, 2017

great solution guys, I love you so much ;)

@kiyeon
Copy link

kiyeon commented Mar 10, 2018

awesome!

@delowar-hosain
Copy link

Working.... Thank You!

@benocd
Copy link

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