expires=$expires;
$this->timeout=$timeout;
$this->cacheena=$cacheena;
$this->debug=$debug;
}
/**
* 检测并创建目录
* @return bool
*/
public function mkdirs(){
if(is_dir($this->path)){
return true;
}else{
return mkdir($this->path, 777, true);
}
}
/**
* 设置缓存文件相关信息
* @param $url
*/
public function setcachefileinfo($url){
$this->url=$url;
$this->path=dirname(__file__).'/cache/';
$this->filename=$this->url?md5($this->url):'null';
}
/**
* 主方法,取得数据
* @param $url
* @return bool|string
*/
public function get($url){
$this->setcachefileinfo($url);
if($this->cacheena) $this->data=unserialize($this->getcache($url));
if(!$this->data) $this->data=$this->curlget($url);
if($this->data && $this->cacheena) $this->setcache($url,serialize($this->data));
return $this->data->contents;
}
/**
* curl get 请求数据
* @param $url
* @return string
*/
public function curlget($url){
if($this->debug && $url=='') echo('请求url为空,请检查');
$return=new stdclass();
$ch = curl_init ();
curl_setopt($ch, curlopt_url,$url );
curl_setopt($ch, curlopt_timeout, $this->timeout);
curl_setopt($ch, curlopt_header, 0 );
curl_setopt($ch, curlopt_returntransfer, 1 );
curl_setopt($ch, curlopt_followlocation, 1);
$this->curldata=curl_exec($ch);
$this->curlheader=curl_getinfo($ch);
$this->curlerror=curl_error($ch);
$return->header=$this->curlheader;
$return->contents=$this->curldata;
curl_close($ch);
if((!$this->curldata || $this->curlheader['http_code'] != '200') && $this->debug ) echo '请求失败,错误信息:'.$this->curlerror;
else return $return;
}
/**
* 取得缓存数据
* @param $url
* @return bool|string
*/
public function getcache($url){
$this->setcachefileinfo($url);
if(file_exists($this->path.$this->filename)){
if(time() - filemtime($this->path.$this->filename) expires) $this->cachedata=file_get_contents($this->path.$this->filename);
else if($this->debug) echo '缓存文件已过期';
if($this->cachedata) return $this->cachedata;else if($this->debug) echo '缓存文件内容为空';
}else{
//if($this->debug) echo '缓存文件不存在';
return false;
}
}
/**
* 写入缓存数据
* @param $url
* @param $data
*/
public function setcache($url,$data){
$this->setcachefileinfo($url);
if(!$this->mkdirs() && $this->debug) echo('创建缓存目录失败:'.$this->path);
if($data){
if(!file_put_contents($this->path.$this->filename,$data) && $this->debug){
echo '写入缓存失败 file:'.$this->path.$this->filename;
}
}else{
if($this->debug) echo '数据为空,不写入缓存';
}
}
}