| 協議 | 加密 | 認證 | 端口 |
| FTP | 明文 | 用戶/密碼 | 21 |
| SFTP | SSH 加密 | 密碼/公鑰 | 22 |
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 分塊讀寫,避免內存溢出。
- 上一篇文章: PHP 通過 COM 元件連接 Access 數據庫(ADODB)完整範例
- 下一篇文章: PHP 遞歸計算目錄總大小並格式化輸出(KB/MB/GB)
Copyright ©
程式碼之家 All Rights Reserved