防盗链就是对一些文件资源进行包装了,这样对方是看不到我们文件源地址了,下载是也是php文件打开了,下载成功之后就成了要下载的文件了,下面我来给各位分享一站长写的类。
悲剧,刚提交的既然服务器挂了没成功,又得重写....
这几天在写一个php防盗链外部资源下载处理函数,昨天晚上刚完成编写,中间遇到了些问题,这里就不详述了;
以下是自写的简单的php防盗链处理类(重新整理编写成类文件,以便后期改进);
代码如下 复制代码
dowurl = $dowurl;
045 // 初始许可资源取用域名列表
046 $this->allowurl = $allowurl;
047 // 初始转跳地址
048 $this->location = $location;
049
050 $this->remoteurl = @parse_url($_server['http_referer']); // 获取来路域名
051 if(!is_array($this->remoteurl))
052 header(http/1.1 301 moved permanently);
053 header(location: .$this->location);
054
055 if(isset($this->remoteurl['host'])){
056 if(in_array($this->remoteurl['host'],$this->allowurl)){ // 判断是否来至许可域名
057 $this->allow = true; // 下载许可状态为:真
058 }
059 }
060 unset($this->allowurl,$this->remoteurl); // 释放内存变量
061 }
062
063 /**
064 * 防盗链资源下载
065 * @access public
066 * @return mixed
067 */
068 public function dow(){
069 $fileinfo = get_headers($this->dowurl,1); // 获取远程文件头部信息
070
071 if(true === $this->allow){ // 判断是否许可下载资源
072 //判断配置文件是否存在
073 if(is_file('config.ini')){
074 $filecon = parse_ini_file('config.ini');
075 }else{
076 $filename = basename($fileinfo['content-location']);
077 $fileconstr = filename = {$filename}rnfileurl = {$fileinfo['content-location']}rnfilesize = {$fileinfo['content-length']};
078 $handle = fopen ('config.ini', wb); // config.ini文件不存在则创建文件
079 if (fwrite ($handle, $fileconstr) == false) { // 数据写入文件
080 echo file creation failed ...;
081 }
082 fclose ($handle); // 关闭一个已打开的文件指针
083 $filecon = parse_ini_file('config.ini');
084 }
085 if(!empty($$this->dowurl)){
086 $fp = @fopen($$this->dowurl, rb); // 二进制模式读取文件
087 if (!$fp)
088 exit(download a mistake.nn);
089
090 // 输出远程资源
091 header(content-type:text/html;charset=utf-8);
092 header('content-description: file transfer');
093 header('content-type: application/octet-stream');
094 header('content-disposition: attachment; filename='.$filecon['filename']);
095 header(accept-ranges: bytes);
096 header('content-transfer-encoding: binary');
097 header('expires: 0');
098 header('cache-control:must-revalidate,post-check=0,pre-check=0');
099 header('pragma: public');
100 header('content-length: '.$filecon['filesize']);
101 while (!feof($fp)){
102 set_time_limit(0); // 设置文件最长执行时间
103 echo fread($fp, 1024); // 输出文件
104 flush(); // 输出缓冲
105 ob_flush(); // 输出缓冲区中的内容
106 }
107 fclose($fp);
108 }else{
109 header(http/1.1 404 not found);
110 }
111 }else{
112 header(http/1.1 301 moved permanently);
113 header(location: .$this->location);
114 }
115 }
116 }
117 // 远程资源地址
118 $dowurl = '/qq/qq5.1/10055/qq5.1.exe';
119 // 转跳地址
120 $location = 'http://www.111cn.net';
121 // 许可来路域名列表
122 $allowurl = array(
123 'blog.emtalk.net',
124 );
125 $burglardow = new burglardow($dowurl,$location,$allowurl);
126 $burglardow -> dow();
有何不足之处,还望访友们多指点指点;