Skip to content

Instantly share code, notes, and snippets.

@waqasy
Forked from jrivero/file_get_contents_curl.php
Created January 2, 2014 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waqasy/8219033 to your computer and use it in GitHub Desktop.
Save waqasy/8219033 to your computer and use it in GitHub Desktop.
<?php
// http://25labs.com/alternative-for-file_get_contents-using-curl/
function file_get_contents_curl($url, $retries=5)
{
$ua = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
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, 5); // 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, 5); // The maximum number of seconds to allow cURL functions to execute.
curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // The maximum number of redirects
$result = trim(curl_exec($ch));
curl_close($ch);
}
else
{
$result = trim(file_get_contents($url));
}
if (empty($result) === true)
{
$result = false;
if ($retries >= 1)
{
sleep(1);
return file_get_contents_curl($url, $retries--);
}
}
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment