首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP FTP操作類封裝:連接、目錄遍歷、文件下載刪除一站式實現

     編輯:PHP 相關知識

類結構設計


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)
  • 加入進度回調回調
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved