封裝php下載文件類

<?php 
	//文件下載
	class NDown{
		private $_file;
		private $_error;
		private $_path;
		//文件目錄和文件名稱
		public function __construct($path = '' , $file){
			$this->_path = $path;
			$this->_file = $file;
		}
		//下載方法
		public function down(){
			$path = $this->_path;
			$file = $this->_file;
			if(!file_exists($path.$file)){
				$this->_error = '文件不存在';
				return false;	
			}
			$fp = fopen($path.$file, 'r'); //打開文件
			$size = filesize($path.$file);
			header('Content-type: application/octet-stream'); //設置輸出流
			header('Accept-Ranges: bytes'); //字節輸出 
			header('Accept-Length: '.$size); //文件長度
			Header("Content-Disposition: attachment; filename=".$file);  //保存的名稱?
			echo fread($fp, $size); //讀入文件並輸出
			fclose($fp);
		}
		public function getError(){
			return $this->_error;
		}
	}
    $obj = new NDown('','1.png');
    $obj->down();
?>

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