這幾天在寫一個PHP防盜鏈外部資源下載處理函數,昨天晚上剛完成編寫,中間遇到了些問題,這裡就不詳述了;
以下是自寫的簡單的PHP防盜鏈處理類(重新整理編寫成類文件,以便後期改進);
復制代碼 代碼如下:
<?php
/**
*
* 防盜鏈外部資源下載處理類
*
* @link http://jb51.net
*
*/
class BurglarDow{
/**
* 初始許可下載狀態
* @var allow
* @access private
*/
private $allow = false;
/**
* 初始下載地址
* @var dowUrl
* @access private
*/
private $dowUrl = null;
/**
* 初始來路域名
* @var RemoteUrl
* @access private
*/
private $RemoteUrl = null;
/**
* 初始許可資源取用域名列表
* @var allowUrl
* @access private
*/
private $allowUrl = array();
/**
* 初始轉跳地址
* @var Location
* @access private
*/
private $Location = null;
public function __construct($dowUrl,$Location,array $allowUrl){
// 初始下載地址
$this->dowUrl = $dowUrl;
// 初始許可資源取用域名列表
$this->allowUrl = $allowUrl;
// 初始轉跳地址
$this->Location = $Location;
$this->RemoteUrl = @parse_url($_SERVER['HTTP_REFERER']); // 獲取來路域名
if(!is_array($this->RemoteUrl))
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$this->Location);
if(isset($this->RemoteUrl['host'])){
if(in_array($this->RemoteUrl['host'],$this->allowUrl)){ // 判斷是否來至許可域名
$this->allow = true; // 下載許可狀態為:真
}
}
unset($this->allowUrl,$this->RemoteUrl); // 釋放內存變量
}
/**
* 防盜鏈資源下載
* @access public
* @return mixed
*/
public function dow(){
$FileInfo = get_headers($this->dowUrl,1); // 獲取遠程文件頭部信息
if(true === $this->allow){ // 判斷是否許可下載資源
//判斷配置文件是否存在
if(is_file('Config.ini')){
$FileCon = parse_ini_file('Config.ini');
}else{
$FileName = basename($FileInfo['Content-Location']);
$FileConStr = "FileName = {$FileName}\r\nFileUrl = {$FileInfo['Content-Location']}\r\nFileSize = {$FileInfo['Content-Length']}";
$handle = fopen ('Config.ini', "wb"); // Config.ini文件不存在則創建文件
if (fwrite ($handle, $FileConStr) == FALSE) { // 數據寫入文件
echo "File creation failed ...";
}
fclose ($handle); // 關閉一個已打開的文件指針
$FileCon = parse_ini_file('Config.ini');
}
if(!empty($$this->dowUrl)){
$fp = @fopen($$this->dowUrl, "rb"); // 二進制模式讀取文件
if (!$fp)
exit("Download a mistake.\n\n");
// 輸出遠程資源
header("Content-type:text/html;charset=utf-8");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$FileCon['FileName']);
header("Accept-Ranges: bytes");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Pragma: public');
header('Content-Length: '.$FileCon['FileSize']);
while (!feof($fp)){
set_time_limit(0); // 設置文件最長執行時間
echo fread($fp, 1024); // 輸出文件
flush(); // 輸出緩沖
ob_flush(); // 輸出緩沖區中的內容
}
fclose($fp);
}else{
header("HTTP/1.1 404 Not Found");
}
}else{
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$this->Location);
}
}
}
// 遠程資源地址
$dowUrl = 'http://dldir1.qq.com/qqfile/qq/QQ5.1/10055/QQ5.1.exe';
// 轉跳地址
$Location = 'http://jb51.net';
// 許可來路域名列表
$allowUrl = array(
'jb51.net',
);
$BurglarDow = new BurglarDow($dowUrl,$Location,$allowUrl);
$BurglarDow -> dow();