-
-
Save steveosoule/3611af5a534c01191594dcca994c6389 to your computer and use it in GitHub Desktop.
php cache curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/cache/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Caching the body of a HTTP response | |
* Licensed under WTFPL | |
* @param $url string | |
* @param $skip_cache bool | |
* @return mixed $data | FALSE | |
*/ | |
function cache_url($url, $skip_cache = FALSE) { | |
// settings | |
$cachetime = 604800; //one week | |
$where = "cache"; | |
if ( ! is_dir($where)) { | |
mkdir($where); | |
} | |
$hash = md5($url); | |
$file = "$where/$hash.cache"; | |
// check the bloody file. | |
$mtime = 0; | |
if (file_exists($file)) { | |
$mtime = filemtime($file); | |
} | |
$filetimemod = $mtime + $cachetime; | |
// if the renewal date is smaller than now, return true; else false (no need for update) | |
if ($filetimemod < time() OR $skip_cache) { | |
$ch = curl_init($url); | |
curl_setopt_array($ch, array( | |
CURLOPT_HEADER => FALSE, | |
CURLOPT_RETURNTRANSFER => TRUE, | |
CURLOPT_USERAGENT => 'Googlebot/2.1 (+http://www.google.com/bot.html)', | |
CURLOPT_FOLLOWLOCATION => TRUE, | |
CURLOPT_MAXREDIRS => 5, | |
CURLOPT_CONNECTTIMEOUT => 15, | |
CURLOPT_TIMEOUT => 30, | |
)); | |
$data = curl_exec($ch); | |
curl_close($ch); | |
// save the file if there's data | |
if ($data AND ! $skip_cache) { | |
file_put_contents($file, $data); | |
} | |
} else { | |
$data = file_get_contents($file); | |
} | |
return $data; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'cache.php'; | |
var_dump(cache_url('http://saltwaterc.ro/', TRUE), cache_url('http://foo.bar/')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment