PHP編程之旅----http、文件下載

<?php
//	關於http協議的各種解析  百度/google
//	防止盜鏈
if(isset($_SERVER["HTTP_REFERER"])){  
	//取出來,判斷是不是https://192.168.1.110/myphp/http開頭
	if(strpos($_SERVER["HTTP_REFERER"],"https://192.168.1.110/myphp/http") == 0){  
		echo "something";  
	}  
} else{ //頁面跳轉
	header("Location: http://www.baidu.com/");  
}  

//頁面無反應,定時跳轉頁面
header("Refresh:3;url=http://www.baudu.com");

//通過header來禁用緩存
header("Expires:-1");
header("Cache-Control:no_cache");
header("Pragma:no-cache");
?>


<?php
	//	download file
	$file = "source.pdf";
	if(!file_exists($file)){
		echo 'file not found';
		exit();
	}
	//	對於存在顯示亂碼的問題,需要在打開文件前對,文件名進行轉碼
	$file=iconv("utf-8","gb2312",$file);  
	// open the file and get size of the file
	$fp = fopen($file,"r");
	$file_size = filesize($file);
	//	開始下載
	header("Content-type:application/octes-stream");
 	//	按照字節大小返回  
    header("Accept-Ranges: bytes");  
    //	返回文件的大小  
    header("Accept-Length: $file_size");  
    //	這裏是客戶端彈出的對話框,對應的文件名  
    header("Content-Disposition: attachment;filename=".$file); 
    //	向客戶端返回數據  
    $buffer=1024;  
    //	爲了下載的安全,我們最好做一個文件字節讀取的計數器  
    $file_count=0;  
    //	判斷文件是否下載結束  
    while(!feof($fp)&&($file_size-$file_count >0)){  
        $file_data=fread($fp,$buffer);  
        //統計讀了多少字節  
        $file_count += $buffer;  
        //把部分數據回送給瀏覽器;  
        echo $file_data;  
    }  
    //關閉文件  
    fclose($fp);  
?>


發佈了40 篇原創文章 · 獲贊 15 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章