我正在使用 PHP cURL 从另一个网站获取信息并将其插入到我的页面中。我想知道是否可以将获取的信息缓存在我的服务器上?例如,当访问者请求一个页面时,信息会被提取并在我的服务器上缓存 24 小时。然后该页面将完全在本地提供 24 小时。当 24 小时到期时,当另一个访问者请求它时,将以相同的方式再次获取和缓存信息。
我目前用来获取信息的代码如下:
$url = $fullURL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
这可能吗?谢谢。
最佳答案
您需要编写或下载一个 php 缓存库(如 extensible php caching library 等)并调整您当前的代码以首先查看缓存。
假设您的缓存库有 2 个函数:
save_cache($result, $cache_key, $timestamp)
和
get_cache($cache_key, $timestamp)
使用 save_cache()
可以将 $result 保存到缓存中,使用 get_cache()
可以检索数据。
$cache_key
将是 md5($fullURL)
,这是缓存库知道您要检索的内容的唯一标识符。
$timestamp
是您希望缓存有效的分钟数/小时数,具体取决于您的缓存库接受的内容。
现在在你的代码上你可以有这样的逻辑:
$cache_key = md5($fullURL);
$timestamp = 24 // assuming your caching library accept hours as timestamp
$result = get_cache($cache_key, $timestamp);
if(!$result){
echo "This url is NOT cached, let's get it and cache it";
// do the curl and get $result
// save the cache:
save_cache($result, $cache_key, $timestamp);
}
else {
echo "This url is cached";
}
echo $result;
关于php - 使用 PHP cURL 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4978427/