類結構設計
class MyFTP {
private $conn;
private $loginResult;
public function connect($host, $user, $pass) {
$this->conn = @ftp_connect($host);
$this->loginResult = @ftp_login($this->conn, $user, $pass);
if (!$this->conn || !$this->loginResult) {
die("FTP連接失敗: $host @ $user");
}
echo "Connected to $host for user $user\n";
}
public function lastModTime($file) {
return ftp_mdtm($this->conn, $file);
}
public function changeDir($dir) {
return ftp_chdir($this->conn, $dir);
}
public function getDir() {
return ftp_pwd($this->conn);
}
public function getFileList($dir) {
return ftp_nlist($this->conn, $dir);
}
public function getFile($remoteFile, $mode = FTP_BINARY, $deleteAfter = false) {
$localFile = basename($remoteFile);
if (@ftp_chdir($this->conn, $remoteFile)) { // 是目錄
ftp_cdup($this->conn);
echo "[DIR] $remoteFile\n";
return false;
}
$result = ftp_get($this->conn, $localFile, $remoteFile, $mode);
if ($deleteAfter) {
if (ftp_delete($this->conn, $remoteFile)) {
echo "Deleted remote $remoteFile\n";
}
}
return $result;
}
public function close() {
ftp_close($this->conn);
}
}
使用示例
$ftp = new MyFTP();
$ftp->connect('ftp.example.com', 'user', 'pass');
$files = $ftp->getFileList('/public/data');
foreach ($files as $file) {
$ftp->getFile($file, FTP_BINARY, true); // 下載並刪除遠程
}
$ftp->close();
擴展建議
- 添加
putFile()上傳功能
- 實現遞歸目錄同步
- 異常處理改用
try/catch (PHP 5+)
- 支持FTPS (ftp_ssl_connect)
- 加入進度回調回調