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

PHP 實現 SFTP 操作教程:基於 SSH2 擴展的上傳、下載與刪除封裝

     編輯:PHP 綜合知識

協議對比

SFTP 基於 SSH2,傳輸內容加密,安全性遠高於 FTP。

FTP 類參考實現(明文,僅教學)

class ftp {
    private $config, $conn;
    public function init($config) { $this->config = $config; }
    public function connect() { return $this->conn = ftp_connect($this->config['host'], $this->config['port']); }
    public function download($remote, $local, $mode='auto') { return @ftp_get($this->conn, $local, $remote, $mode); }
    public function upload($remote, $local, $mode='auto') { return @ftp_put($this->conn, $remote, $local, $mode); }
    public function remove($remote) { return @ftp_delete($this->conn, $remote); }
}

SFTP 類完整實現(支援密碼/公鑰)

class sftp {
    private $config, $conn, $use_pubkey = false;
    public function init($config) { $this->config = $config; }
    public function connect() {
        $methods = $this->use_pubkey ? ['hostkey'=>'ssh-rsa'] : [];
        $this->conn = ssh2_connect($this->config['host'], $this->config['port'], $methods);
        if ($this->use_pubkey) {
            return ssh2_auth_pubkey_file($this->conn, $this->config['user'],
                $this->config['pubkey_path'], $this->config['privkey_path'], $this->config['passphrase'] ?? '');
        } else {
            return ssh2_auth_password($this->conn, $this->config['user'], $this->config['passwd']);
        }
    }
    public function download($remote, $local) { return ssh2_scp_recv($this->conn, $remote, $local); }
    public function upload($remote, $local, $mode=0664) { return ssh2_scp_send($this->conn, $local, $remote, $mode); }
    public function remove($remote) {
        $sftp = ssh2_sftp($this->conn);
        if (is_dir("ssh2.sftp://{$sftp}/{$remote}")) return ssh2_sftp_rmdir($sftp, $remote);
        else return ssh2_sftp_unlink($sftp, $remote);
    }
}

使用示例

$config = [
    "host" => "192.168.1.1", "port" => 22,
    "user" => "user", "passwd" => "password",
    // 公鑰認證時:
    // "use_pubkey" => true, "pubkey_path" => "/root/.ssh/id_rsa.pub", "privkey_path" => "/root/.ssh/id_rsa", "passphrase" => ""
];
$handle = new sftp();
$handle->init($config);
$handle->connect();
$handle->download('/remote/file.txt', '/local/file.txt');
$handle->upload('/remote/put.txt', '/local/put.txt');
$handle->remove('/remote/old.txt');

注意事項

  • 需安裝 ssh2 PHP 擴展(pecl install ssh2)。
  • 公鑰文件權限建議 600,私鑰 400。
  • 大文件傳輸建議啟用 ssh2_sftp 流包裝器配合 fopen 分塊讀寫,避免內存溢出。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
協議加密認證端口
FTP明文用戶/密碼21
SFTPSSH 加密密碼/公鑰22