PHP 內建 FTP 擴展提供完整的 FTP 客戶端功能。本文總結核心函數並提供一個可復用的上傳類,支持被動模式、錯誤處理、大文件分塊上傳。
| 函數 | 說明 |
|---|---|
| ftp_connect(host, port, timeout) | 建立連接,默認端口 21 |
| ftp_login(conn, user, pass) | 登錄認證 |
| ftp_pasv(conn, true) | 開啟被動模式(穿透防火牆/NAT 必須) |
| ftp_put(conn, remote, local, mode) | 上傳文件,mode: FTP_ASCII/FTP_BINARY |
| ftp_get(conn, local, remote, mode) | 下載文件 |
| ftp_mkdir(conn, dir) | 創建遠程目錄 |
| ftp_chdir(conn, dir) | 切換遠程目錄 |
| ftp_close(conn) | 關閉連接 |
<?php
$host = 'ftp.example.com';
$user = 'username';
$pass = 'password';
$localFile = 'local.txt';
$remoteFile = 'remote.txt';
$conn = ftp_connect($host) or die('連接失敗');
ftp_login($conn, $user, $pass) or die('登錄失敗');
ftp_pasv($conn, true); // 關鍵:被動模式
// 二進制模式上傳(圖片、壓縮包等必須用 BINARY)
if (ftp_put($conn, $remoteFile, $localFile, FTP_BINARY)) {
echo '上傳成功';
} else {
echo '上傳失敗';
}
ftp_close($conn);
?>
<?php
class FtpClient {
private $conn;
private $config;
public function __construct(array $config) {
$this->config = $config;
}
public function connect(): bool {
$this->conn = @ftp_connect($this->config['host'], $this->config['port'] ?? 21, $this->config['timeout'] ?? 30);
if (!$this->conn) throw new Exception('FTP 連接失敗');
if (!@ftp_login($this->conn, $this->config['user'], $this->config['pass'])) {
throw new Exception('FTP 登錄失敗');
}
ftp_pasv($this->conn, true);
return true;
}
public function upload(string $local, string $remote, int $mode = FTP_BINARY): bool {
if (!is_file($local)) throw new Exception("本地文件不存在: $local");
// 確保遠程目錄存在
$this->ensureDir(dirname($remote));
return ftp_put($this->conn, $remote, $local, $mode);
}
private function ensureDir(string $dir): void {
$dirs = explode('/', trim($dir, '/'));
$path = '';
foreach ($dirs as $d) {
$path .= "/$d";
@ftp_chdir($this->conn, $path) ?: @ftp_mkdir($this->conn, $path);
}
}
public function disconnect(): void {
if ($this->conn) ftp_close($this->conn);
}
public function __destruct() { $this->disconnect(); }
}
// 使用
$ftp = new FtpClient([
'host' => 'ftp.example.com',
'user' => 'user',
'pass' => 'pass',
'port' => 21
]);
$ftp->connect();
$ftp->upload('data/backup.zip', 'backups/2024/backup.zip');
$ftp->disconnect();
ftp_nb_put 非阻塞上傳,配合進度條。ftp_size)與 MD5,確保完整性。--with-openssl 並使用 ftp_ssl_connect。false,務必檢查並拋出異常或記錄日志。