<?php
/**
* 作用:FTP操作類( 拷貝、移動、刪除文件/創建目錄 )
*/
class ftp
{
public $off; // 返回操作狀態(成功/失敗)
public $conn_id; // FTP連接
/* const FTP_HOST='121.42.139.124';
const FTP_PORT='21';
const FTP_USER='ceshi';
const FTP_PASS='123456'; */
const FTP_HOST='14.23.125.68';
const FTP_PORT='21';
const FTP_USER='RLGZB1B090Z';
const FTP_PASS='B1B090Z';
/**
* 方法:FTP連接
* @FTP_HOST -- FTP主機
* @FTP_PORT -- 端口
* @FTP_USER -- 用戶名
* @FTP_PASS -- 密碼
*/
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)
return "文件上傳失敗,請檢查權限及路徑是否正確!";
else
return '上傳成功';
}
/**
* 方法:移動文件
* @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) return "文件移動失敗,請檢查權限及原路徑是否正確!";
}
/**
* 方法:複製文件
* 說明:由於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) return "文件複製失敗,請檢查權限及原路徑是否正確!";
$this->up_file($downpath,$newpath,$type);
}
/**
* 方法:刪除文件
* @path -- 路徑
*/
function del_file($path)
{
$this->off = @ftp_delete($this->conn_id,$path);
if(!$this->off) return "文件刪除失敗,請檢查權限及路徑是否正確!";
}
/**
* 方法:生成目錄
* @path -- 路徑
*/
function dir_mkdirs($path)
{
$path_arr = explode('/',$path); // 取目錄數組
$file_name = array_pop($path_arr); // 彈出文件名
$path_div = 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)
{
return "目錄創建失敗,請檢查權限及路徑是否正確!";
exit;
}
@ftp_chdir($this->conn_id,$val);
}
}
for($i=1;$i=$path_div;$i++) // 回退到根
{
@ftp_cdup($this->conn_id);
}
}
/**
* 方法:關閉FTP連接
*/
function close()
{
@ftp_close($this->conn_id);
}
}
// class class_ftp end
/************************************** 測試 ***********************************
$ftp = new class_ftp('192.168.100.143',21,'user','pwd'); // 打開FTP連接
//$ftp->up_file('aa.txt','a/b/c/cc.txt'); // 上傳文件
//$ftp->move_file('a/b/c/cc.txt','a/cc.txt'); // 移動文件
//$ftp->copy_file('a/cc.txt','a/b/dd.txt'); // 複製文件
//$ftp->del_file('a/b/dd.txt'); // 刪除文件
$ftp->close(); // 關閉FTP連接
******************************************************************************/
php常用類之ftp文件操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.