Skip to content

Instantly share code, notes, and snippets.

@denchev
Last active August 29, 2015 14:07
Show Gist options
  • Save denchev/cb3f3d0af86657d7afef to your computer and use it in GitHub Desktop.
Save denchev/cb3f3d0af86657d7afef to your computer and use it in GitHub Desktop.
Get remote URL content
<?php
function request($url, $cache = false) {
$prefix = 'cache_response_';
if($cache === true) {
$folder = dirname(__FILE__ ) . DIRECTORY_SEPARATOR . 'cache';
$folder = file_exists($folder) && is_writable($folder) ? $folder : '/tmp';
$file = $folder . '/' . $prefix . md5($url);
if(file_exists($file)) {
$response = file_get_contents($file);
return $response;
}
}
$ch = curl_init();
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$error = curl_error($ch);
$errno = curl_errno($ch);
$info = curl_getinfo($ch);
if($info['http_code'] == 504 || $errno == 28) {
throw new Exception("Unable to open url: " . $url);
}
curl_close($ch);
if($cache === true) {
file_put_contents($file, $response);
}
return $response;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment