來源:不言 發(fā)布時(shí)間:2018-12-13 15:38:23 閱讀量:868
本篇文章給大家?guī)淼膬?nèi)容是關(guān)于php中ftp的上傳和下載功能的實(shí)現(xiàn)代碼,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。
/** * 作用:FTP操作類( 拷貝、移動(dòng)、刪除文件/創(chuàng)建目錄 ) */ class FTP { public $off; // 返回操作狀態(tài)(成功/失敗) public $conn_id; // FTP連接 /** * 方法:FTP連接 * @FTP_HOST -- FTP主機(jī) * @FTP_PORT -- 端口 * @FTP_USER -- 用戶名 * @FTP_PASS -- 密碼 */ const FTP_HOST='xxx.xx.xx.xxx'; const FTP_PORT='21'; const FTP_USER='xx'; const FTP_PASS='xxxx'; function __construct() { $this->conn_id = @ftp_connect(self::FTP_HOST,self::FTP_PORT) or die("FTP服務(wù)器連接失敗"); @ftp_login($this->conn_id,self::FTP_USER,self::FTP_PASS) or die("FTP服務(wù)器登陸失敗"); @ftp_pasv($this->conn_id,1); // 打開被動(dòng)模擬 } /** * 方法:上傳文件 * @path -- 本地路徑 * @newpath -- 上傳路徑 * @type -- 若目標(biāo)目錄不存在則新建 */ function up_file($path,$newpath,$type=true) { if($type) $this->dir_mkdirs($newpath); $this->off = @ftp_put($this->conn_id,$newpath,$path,FTP_BINARY); if(!$this->off) echo "文件上傳失敗,請檢查權(quán)限及路徑是否正確!"; } /** * 方法:移動(dòng)文件 * @path -- 原路徑 * @newpath -- 新路徑 * @type -- 若目標(biāo)目錄不存在則新建 */ function move_file($path,$newpath,$type=true) { if($type) $this->dir_mkdirs($newpath); $this->off = @ftp_rename($this->conn_id,$path,$newpath); if(!$this->off) echo "文件移動(dòng)失敗,請檢查權(quán)限及原路徑是否正確!"; } /** * 方法:復(fù)制文件 * 說明:由于FTP無復(fù)制命令,本方法變通操作為:下載后再上傳到新的路徑 * @path -- 原路徑 * @newpath -- 新路徑 * @type -- 若目標(biāo)目錄不存在則新建 */ function copy_file($path,$newpath,$type=true) { $downpath = "c:/tmp.dat"; $this->off = @ftp_get($this->conn_id,$downpath,$path,FTP_BINARY);// 下載 if(!$this->off) echo "文件復(fù)制失敗,請檢查權(quán)限及原路徑是否正確!"; $this->up_file($downpath,$newpath,$type); } /** * 方法:刪除文件 * @path -- 路徑 */ function del_file($path) { $this->off = @ftp_delete($this->conn_id,$path); return $this->off; } /** * 方法:生成目錄 * @path -- 路徑 */ function dir_mkdirs($path) { $path_arr = explode('/',$path); // 取目錄數(shù)組 $file_name = array_pop($path_arr); // 彈出文件名 $path_p = count($path_arr); // 取層數(shù) foreach($path_arr as $val) // 創(chuàng)建目錄 { if(@ftp_chdir($this->conn_id,$val) == FALSE) { $tmp = @ftp_mkdir($this->conn_id,$val); if($tmp == FALSE) { echo "目錄創(chuàng)建失敗,請檢查權(quán)限及路徑是否正確!"; exit; } @ftp_chdir($this->conn_id,$val); } } for($i=1;$i<=$path_p;$i++) // 回退到根 { @ftp_cdup($this->conn_id); } } /* * 文件下載 */ function download($select_file) { $tmpfile = tempnam( getcwd()."/", "temp" ); // 創(chuàng)建唯一的臨時(shí)文件 if(ftp_get($this->conn_id, $tmpfile, $select_file, FTP_BINARY)) { // 下載指定的文件到臨時(shí)文件 $this->close(); // 關(guān)閉連接 $file = explode('/',$select_file); $file = end($file); header("content-type: application/octet-stream"); header("content-disposition: attachment; filename=" . $file);//content-disposition:inline; 表示可以在線打開文件! readfile($tmpfile); unlink($tmpfile); // 刪除臨時(shí)文件 exit; } unlink($tmpfile); } /** * 方法:關(guān)閉FTP連接 */ function close() { @ftp_close($this->conn_id); } }