SFTP(SSH File Transfer Protocol)基於 SSH 協議,提供加密的文件傳輸通道,是替代傳統 FTP 的安全選擇。本文系統介紹 FTP/SSH/SFTP 協議差異,並提供 PHP 操作 FTP 與 SFTP 的類封裝代碼。
| 協議 | 傳輸加密 | 端口 | 認證方式 | 備註 |
|---|---|---|---|---|
| FTP | 明文 | 21/20 | 用戶名/密碼 | 需開啟數據端口,穿透防火牆困難 |
| SSH | 全程加密 | 22 | 密碼/公鑰 | 安全遠程登錄協議 |
| SFTP | 全程加密 | 22 (隨 SSH) | 密碼/公鑰 | SSH 子系統,單通道,穿透防火牆易 |
| FTPS | SSL/TLS 加密 | 990/989 | 用戶名/密碼 | FTP over SSL,雙通道問題依然存在 |
class Ftp {
private $config = null;
private $conn = null;
public function init($config) { $this->config = $config; }
public function connect() {
return $this->conn = ftp_connect($this->config['host'], $this->config['port']);
}
public function login() {
return @ftp_login($this->conn, $this->config['username'], $this->config['password']);
}
// 下載:$mode 可為 FTP_BINARY / FTP_ASCII
public function download($remote, $local, $mode = FTP_BINARY) {
return @ftp_get($this->conn, $local, $remote, $mode);
}
// 上傳
public function upload($local, $remote, $mode = FTP_BINARY) {
return @ftp_put($this->conn, $remote, $local, $mode);
}
public function delete($remote) {
return @ftp_delete($this->conn, $remote);
}
public function close() {
@ftp_close($this->conn);
}
}
// 使用
$config = ['host'=>'localhost','username'=>'root','password'=>'root','port'=>21];
$ftp = new Ftp();
$ftp->init($config);
$ftp->connect();
$ftp->login();
$ftp->upload('local.log', 'remote.log');
$ftp->download('remote.log', 'local_copy.log');
$ftp->close();
需安裝 pecl install ssh2 並啟用擴展。
class Sftp {
private $conn;
private $sftp;
public function connect($host, $port = 22) {
$this->conn = ssh2_connect($host, $port);
return $this->conn !== false;
}
public function authPassword($username, $password) {
return ssh2_auth_password($this->conn, $username, $password);
}
public function authPubkey($username, $pubkeyFile, $privkeyFile, $passphrase = null) {
return ssh2_auth_pubkey_file($this->conn, $username, $pubkeyFile, $privkeyFile, $passphrase);
}
public function initSftp() {
$this->sftp = ssh2_sftp($this->conn);
return $this->sftp !== false;
}
// 遠程路徑需加前綴 "ssh2.sftp://ResourceID/"
public function upload($local, $remote) {
$stream = fopen("ssh2.sftp://{$this->sftp}{$remote}", 'w');
$data = file_get_contents($local);
$result = fwrite($stream, $data);
fclose($stream);
return $result !== false;
}
public function download($remote, $local) {
$stream = fopen("ssh2.sftp://{$this->sftp}{$remote}", 'r');
$data = stream_get_contents($stream);
fclose($stream);
return file_put_contents($local, $data) !== false;
}
public function listDir($remote) {
return ssh2_sftp_stat($this->sftp, $remote);
}
}
// 使用
$sftp = new Sftp();
$sftp->connect('192.168.1.100');
$sftp->authPassword('user', 'pass');
$sftp->initSftp();
$sftp->upload('/local/file.txt', '/remote/file.txt');
$sftp->download('/remote/file.txt', '/local/file.txt');
SFTP 以單通道、強加密、易穿透防火牆的優勢,成為現代文件傳輸的標準選擇。PHP 通過 ssh2 擴展原生支援,封裝後即可在業務中安全高效地進行文件交換。