萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP FTP 客戶端實作:自動化部署與檔案同步完整指南

FTP 核心函數速查

函數用途回傳值
ftp_connect()建立 FTP 連線resource|false
ftp_ssl_connect()建立 FTPS (SSL) 連線resource|false
ftp_login()登入驗證bool
ftp_pasv()設定被動模式 (穿透防火牆必開)bool
ftp_put()上傳檔案bool
ftp_fput()從檔案指標上傳 (大檔案)bool
ftp_get()下載檔案bool
ftp_fget()下載到檔案指標bool
ftp_mkdir()建立目錄bool
ftp_chdir()切換目錄bool
ftp_nlist()列出目錄檔案array|false
ftp_mlsd()詳細列表 (MLSD 指令)array|false
ftp_delete()刪除檔案bool
ftp_rmdir()刪除目錄bool
ftp_rename()重命名/移動bool
ftp_chmod()修改權限bool
ftp_size()取得檔案大小int|-1
ftp_mdtm()取得修改時間int|-1
ftp_close()關閉連線bool

完整 FTP 客戶端類

<?php
declare(strict_types=1);

class FtpClient
{
    private $conn;
    private string $host;
    private int $port;
    private int $timeout;
    private bool $passive = true;
    private bool $ssl = false;
    
    public function __construct(
        string $host, 
        int $port = 21, 
        int $timeout = 30,
        bool $ssl = false
    ) {
        $this->host = $host;
        $this->port = $port;
        $this->timeout = $timeout;
        $this->ssl = $ssl;
    }
    
    public function connect(): bool
    {
        $this->conn = $this->ssl 
            ? @ftp_ssl_connect($this->host, $this->port, $this->timeout)
            : @ftp_connect($this->host, $this->port, $this->timeout);
            
        if (!$this->conn) {
            throw new RuntimeException("無法連線至 FTP 伺服器: {$this->host}:{$this->port}");
        }
        return true;
    }
    
    public function login(string $username, string $password): bool
    {
        if (!@ftp_login($this->conn, $username, $password)) {
            throw new RuntimeException("FTP 登入失敗: 用戶名或密碼錯誤");
        }
        
        // 被動模式:客戶端主動發起資料連線,穿透防火牆/NAT
        if (!@ftp_pasv($this->conn, true)) {
            throw new RuntimeException("無法啟用被動模式");
        }
        
        // 設定二進位模式 (預防 ASCII 模式損壞二進位檔案)
        @ftp_type($this->conn, FTP_BINARY);
        
        return true;
    }
    
    public function upload(string $localPath, string $remotePath, int $mode = FTP_BINARY): bool
    {
        if (!file_exists($localPath)) {
            throw new InvalidArgumentException("本地檔案不存在: $localPath");
        }
        
        $this->ensureRemoteDir(dirname($remotePath));
        
        // 大檔案使用 ftp_fput 串流上傳
        $handle = fopen($localPath, 'rb');
        if (!$handle) throw new RuntimeException("無法開啟本地檔案: $localPath");
        
        $result = ftp_fput($this->conn, $remotePath, $handle, $mode);
        fclose($handle);
        
        if (!$result) {
            throw new RuntimeException("上傳失敗: $localPath -> $remotePath");
        }
        
        return true;
    }
    
    public function download(string $remotePath, string $localPath, int $mode = FTP_BINARY): bool
    {
        $this->ensureLocalDir(dirname($localPath));
        
        $handle = fopen($localPath, 'wb');
        if (!$handle) throw new RuntimeException("無法建立本地檔案: $localPath");
        
        $result = ftp_fget($this->conn, $handle, $remotePath, $mode);
        fclose($handle);
        
        if (!$result) {
            @unlink($localPath); // 清理不完整檔案
            throw new RuntimeException("下載失敗: $remotePath -> $localPath");
        }
        
        return true;
    }
    
    public function syncDirectory(string $localDir, string $remoteDir, array $options = []): array
    {
        $options = array_merge([
            'delete_remote' => false,   // 刪除遠端多餘檔案
            'dry_run' => false,         // 僅模擬
            'compare' => 'mtime_size',  // 比較方式: mtime_size, hash
        ], $options);
        
        $results = ['uploaded' => [], 'deleted' => [], 'skipped' => [], 'errors' => []];
        
        // 掃描本地檔案
        $localFiles = $this->scanLocal($localDir);
        $remoteFiles = $this->scanRemote($remoteDir);
        
        foreach ($localFiles as $relPath => $localInfo) {
            $remotePath = $remoteDir . '/' . $relPath;
            $remoteInfo = $remoteFiles[$relPath] ?? null;
            
            $shouldUpload = false;
            if (!$remoteInfo) {
                $shouldUpload = true; // 新檔案
            } elseif ($this->fileChanged($localInfo, $remoteInfo, $options['compare'])) {
                $shouldUpload = true; // 檔案有變更
            }
            
            if ($shouldUpload) {
                if (!$options['dry_run']) {
                    try {
                        $this->upload($localInfo['path'], $remotePath);
                        $results['uploaded'][] = $relPath;
                    } catch (Throwable $e) {
                        $results['errors'][] = "$relPath: " . $e->getMessage();
                    }
                } else {
                    $results['uploaded'][] = "[DRY] $relPath";
                }
            } else {
                $results['skipped'][] = $relPath;
            }
        }
        
        // 刪除遠端多餘檔案
        if ($options['delete_remote']) {
            foreach ($remoteFiles as $relPath => $remoteInfo) {
                if (!isset($localFiles[$relPath])) {
                    $remotePath = $remoteDir . '/' . $relPath;
                    if (!$options['dry_run']) {
                        try {
                            $this->delete($remotePath);
                            $results['deleted'][] = $relPath;
                        } catch (Throwable $e) {
                            $results['errors'][] = "$relPath: " . $e->getMessage();
                        }
                    } else {
                        $results['deleted'][] = "[DRY] $relPath";
                    }
                }
            }
        }
        
        return $results;
    }
    
    private function scanLocal(string $dir): array
    {
        $files = [];
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $relPath = substr($file->getPathname(), strlen($dir) + 1);
                $files[str_replace('\\', '/', $relPath)] = [
                    'path' => $file->getPathname(),
                    'size' => $file->getSize(),
                    'mtime' => $file->getMTime(),
                    'hash' => null, // 惰性計算
                ];
            }
        }
        return $files;
    }
    
    private function scanRemote(string $dir): array
    {
        $files = [];
        $this->ftpMlsdRecursive($dir, $dir, $files);
        return $files;
    }
    
    private function ftpMlsdRecursive(string $baseDir, string $currentDir, array &$files): void
    {
        $list = @ftp_mlsd($this->conn, $currentDir);
        if ($list === false) return; // 目錄不存在或無權限
        
        foreach ($list as $name => $info) {
            if ($name === '.' || $name === '..') continue;
            
            $fullPath = $currentDir . '/' . $name;
            $relPath = substr($fullPath, strlen($baseDir) + 1);
            
            if ($info['type'] === 'file') {
                $files[$relPath] = [
                    'size' => (int)$info['size'],
                    'mtime' => strtotime($info['modify']),
                    'hash' => null,
                ];
            } elseif ($info['type'] === 'dir') {
                $this->ftpMlsdRecursive($baseDir, $fullPath, $files);
            }
        }
    }
    
    private function fileChanged(array $local, array $remote, string $method): bool
    {
        return match($method) {
            'mtime_size' => $local['size'] !== $remote['size'] || $local['mtime'] !== $remote['mtime'],
            'size' => $local['size'] !== $remote['size'],
            'mtime' => $local['mtime'] !== $remote['mtime'],
            'hash' => $this->computeHash($local['path']) !== ($remote['hash'] ?? $this->computeRemoteHash($remote['path'])),
            default => true,
        };
    }
    
    private function computeHash(string $path): string
    {
        return hash_file('sha256', $path);
    }
    
    private function computeRemoteHash(string $remotePath): string
    {
        // 遠端雜湊需下載計算,較慢。建議僅在必要時使用。
        $tmp = sys_get_temp_dir() . '/ftp_hash_' . uniqid();
        $this->download($remotePath, $tmp);
        $hash = hash_file('sha256', $tmp);
        unlink($tmp);
        return $hash;
    }
    
    private function ensureRemoteDir(string $dir): void
    {
        if ($dir === '.' || $dir === '/') return;
        
        $parts = explode('/', trim($dir, '/'));
        $current = '';
        foreach ($parts as $part) {
            $current .= '/' . $part;
            if (!@ftp_chdir($this->conn, $current)) {
                @ftp_mkdir($this->conn, $current);
                @ftp_chdir($this->conn, $current);
            }
        }
        // 回到根目錄
        @ftp_chdir($this->conn, '/');
    }
    
    private function ensureLocalDir(string $dir): void
    {
        if (!is_dir($dir)) mkdir($dir, 0755, true);
    }
    
    public function delete(string $remotePath): bool
    {
        return @ftp_delete($this->conn, $remotePath);
    }
    
    public function disconnect(): void
    {
        if ($this->conn) {
            @ftp_close($this->conn);
            $this->conn = null;
        }
    }
    
    public function __destruct()
    {
        $this->disconnect();
    }
}
?>

自動化部署腳本範例

<?php
// deploy.php
require 'FtpClient.php';

$config = [
    'host' => 'ftp.example.com',
    'port' => 21,
    'username' => 'deploy_user',
    'password' => 'secure_password',
    'ssl' => true, // FTPS
    'local_dir' => __DIR__ . '/dist',
    'remote_dir' => '/public_html',
    'delete_remote' => true,
    'dry_run' => false, // 首次執行設 true 確認
];

try {
    $ftp = new FtpClient($config['host'], $config['port'], 60, $config['ssl']);
    $ftp->connect();
    $ftp->login($config['username'], $config['password']);
    
    echo "開始同步: {$config['local_dir']} -> {$config['remote_dir']}\n";
    
    $results = $ftp->syncDirectory(
        $config['local_dir'],
        $config['remote_dir'],
        [
            'delete_remote' => $config['delete_remote'],
            'dry_run' => $config['dry_run'],
            'compare' => 'mtime_size',
        ]
    );
    
    echo "上傳: " . count($results['uploaded']) . " 個檔案\n";
    echo "刪除: " . count($results['deleted']) . " 個檔案\n";
    echo "跳過: " . count($results['skipped']) . " 個檔案\n";
    
    if ($results['errors']) {
        echo "錯誤:\n";
        foreach ($results['errors'] as $err) echo "  - $err\n";
    }
    
    $ftp->disconnect();
    echo $config['dry_run'] ? "\n[DRY RUN] 未實際執行\n" : "\n部署完成!\n";
    
} catch (Throwable $e) {
    echo "部署失敗: " . $e->getMessage() . "\n";
    exit(1);
}
?>

進階:支援 SFTP (SSH2)

FTP 明文傳輸不安全,生產環境強烈建議使用 SFTP (SSH File Transfer Protocol):

<?php
// 需安裝 ssh2 擴展: pecl install ssh2
class SftpClient
{
    private $conn;
    private $sftp;
    
    public function __construct(string $host, int $port = 22)
    {
        $this->conn = ssh2_connect($host, $port);
        if (!$this->conn) throw new Exception("SSH 連線失敗");
    }
    
    public function login(string $username, string $password = null, string $pubkey = null, string $privkey = null): bool
    {
        if ($pubkey && $privkey) {
            return ssh2_auth_pubkey_file($this->conn, $username, $pubkey, $privkey);
        }
        return ssh2_auth_password($this->conn, $username, $password);
    }
    
    public function upload(string $local, string $remote): bool
    {
        $this->sftp = $this->sftp ?? ssh2_sftp($this->conn);
        return ssh2_scp_send($this->conn, $local, $remote, 0644);
    }
    
    public function download(string $remote, string $local): bool
    {
        $this->sftp = $this->sftp ?? ssh2_sftp($this->conn);
        return ssh2_scp_recv($this->conn, $remote, $local);
    }
    
    // 更完整功能建議使用 phpseclib/phpseclib (純 PHP SFTP)
}
?>

常見問題排查

問題原因解決
連線逾時防火牆阻擋 21 埠或被動模式埠範圍開啟防火牆、設定 FTP 伺服器被動模式埠範圍、Nginx/防火牆放行
上傳 0 位元組ASCII 模式傳輸二進位檔強制 ftp_type($conn, FTP_BINARY)
中文檔名亂碼編碼不一致檔名 URL 編碼、或設定伺服器 UTF-8
權限拒絕目錄不存在或無寫入權限遞歸建立目錄 ftp_mkdir、檢查用戶權限
大檔案中斷執行時間/記憶體限制用 ftp_fput 串流、調大 max_execution_time

總結

PHP FTP 操作核心在於:被動模式 (ftp_pasv)、二進位模式 (FTP_BINARY)、串流上傳下載 (ftp_fput/ftp_fget)、目錄遞歸建立、錯誤處理與資源釋放。生產環境自動化部署建議:改用 SFTP/SSH2 確保傳輸加密,或使用 phpseclib/phpseclib 純 PHP 實現免擴展依賴。同步邏輯採用「本地為準、比對 mtime+size、可選雜湊驗證」策略,支援干跑模式驗證。

copyright © 萬盛學電腦網 all rights reserved