使用PHP cURL缓存 [英] Cache using PHP cURL

查看:456
本文介绍了使用PHP cURL缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP cURL从其他网站获取信息,并将其插入我的网页。我想知道是否可能将获取的信息缓存在我的服务器上?例如,当访问者请求页面时,信息会在我的服务器上提取并缓存24小时。然后该页面在本地完全提供24小时。当24小时过期后,当另一个访问者以同样方式请求时,会再次提取并缓存信息。

I'm using PHP cURL to fetch information from another website and insert it into my page. I was wondering if it was possible to have the fetched information cached on my server? For example, when a visitor requests a page, the information is fetched and cached on my server for 24 hours. The page is then entirely served locally for 24 hours. When the 24 hours expire, the information is again fetched and cached when another visitor requests it, in the same way.

我当前用于获取信息的代码是如下:

The code I am currently using to fetch the information is as follows:

$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缓存库(如可扩展php缓存库等)并调整您当前的代码,首先看看缓存。

You need to write or download a php caching library (like extensible php caching library or such) and adjust your current code to first take a look at cache.

假设您的缓存库有两个函数:

Let's say your cache library has 2 functions called:

save_cache($result, $cache_key, $timestamp)

get_cache($cache_key, $timestamp)

save_cache()您将保存$结果到缓存中,并且 get_cache()您将检索数据。

With save_cache() you will save the $result into the cache and with get_cache() you will retrieve the data.

$ cache_key 会是 md5($ fullURL),缓存的唯一标识符库知道你想要检索什么。

$cache_key would be md5($fullURL), a unique identifier for the caching library to know what you want to retrieve.

$ timestamp 是您希望高速缓存有效的分钟数/小时数,具体取决于您的缓存库接受。

$timestamp is the amount of minutes/hours you want the cache to be valid, depending on what your caching library accepts.

现在你的代码你可以有一个逻辑如:

Now on your code you can have a logic like:

$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 cURL缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆