本篇文章給大家帶來的內容是關於php中ftp的上傳和下載功能的實現代碼,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
/**
* 作用:FTP操作類( 拷貝、移動、刪除文件/創建目錄 )
*/
class FTP
{
public $off; // 返回操作狀態(成功/失敗)
public $conn_id; // FTP連接
/**
* 方法:FTP連接
* @FTP_HOST -- FTP主機
* @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服務器連接失敗");
@ftp_login($this->conn_id,self::FTP_USER,self::FTP_PASS) or die("FTP服務器登陸失敗");
@ftp_pasv($this->conn_id,1); // 打開被動模擬
}
/**
* 方法:上傳文件
* @path -- 本地路徑
* @newpath -- 上傳路徑
* @type -- 若目標目錄不存在則新建
*/
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 "文件上傳失敗,請檢查權限及路徑是否正確!";
}
/**
* 方法:移動文件
* @path -- 原路徑
* @newpath -- 新路徑
* @type -- 若目標目錄不存在則新建
*/
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 "文件移動失敗,請檢查權限及原路徑是否正確!";
}
/**
* 方法:複製文件
* 說明:由於FTP無複製命令,本方法變通操作為:下載後再上傳到新的路徑
* @path -- 原路徑
* @newpath -- 新路徑
* @type -- 若目標目錄不存在則新建
*/
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 "文件複製失敗,請檢查權限及原路徑是否正確!";
$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); // 取目錄數組
$file_name = array_pop($path_arr); // 彈出文件名
$path_p = count($path_arr); // 取層數
foreach($path_arr as $val) // 創建目錄
{
if(@ftp_chdir($this->conn_id,$val) == FALSE)
{
$tmp = @ftp_mkdir($this->conn_id,$val);
if($tmp == FALSE)
{
echo "目錄創建失敗,請檢查權限及路徑是否正確!";
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" ); // 創建唯一的臨時文件
if(ftp_get($this->conn_id, $tmpfile, $select_file, FTP_BINARY)) { // 下載指定的文件到臨時文件
$this->close(); // 關閉連接
$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); // 刪除臨時文件
exit;
}
unlink($tmpfile);
}
/**
* 方法:關閉FTP連接
*/
function close()
{
@ftp_close($this->conn_id);
}
}
閱讀更多 美食代碼喵 的文章