php实现sftp上传
使用 PHP 的 SSH2 扩展实现 SFTP 上传
确保服务器已安装 ssh2 PHP 扩展,可通过 php -m | grep ssh2 检查。若未安装,需通过 pecl install ssh2 或系统包管理器安装。
连接 SFTP 服务器并上传文件:
$host = 'sftp.example.com';
$port = 22;
$username = 'your_username';
$password = 'your_password';
$localFile = '/path/to/local/file.txt';
$remoteFile = '/path/to/remote/file.txt';
$connection = ssh2_connect($host, $port);
if (!ssh2_auth_password($connection, $username, $password)) {
throw new Exception('Authentication failed');
}
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://{$sftp}{$remoteFile}", 'w');
if (!$stream) {
throw new Exception('Could not open remote file');
}
$fileContent = file_get_contents($localFile);
if (fwrite($stream, $fileContent) === false) {
throw new Exception('Could not write to remote file');
}
fclose($stream);
ssh2_disconnect($connection);
使用 PHP 的 SFTP 库(phpseclib)
通过 Composer 安装 phpseclib:
composer require phpseclib/phpseclib
代码实现:
use phpseclib3\Net\SFTP;
$sftp = new SFTP('sftp.example.com');
if (!$sftp->login('username', 'password')) {
throw new Exception('Login failed');
}
$localFile = '/path/to/local/file.txt';
$remoteFile = '/path/to/remote/file.txt';
if (!$sftp->put($remoteFile, $localFile, SFTP::SOURCE_LOCAL_FILE)) {
throw new Exception('Upload failed');
}
错误处理与调试
增加详细的错误处理机制:
try {
$sftp = new SFTP('sftp.example.com');
$sftp->login('username', 'password');
if ($sftp->put('remote.txt', 'local.txt')) {
echo "Upload successful";
} else {
echo "Upload failed: " . $sftp->getLastError();
}
} catch (Exception $e) {
echo "SFTP error: " . $e->getMessage();
}
文件权限设置
上传后修改远程文件权限:
$sftp->chmod(0644, $remoteFile);
大文件分块上传
对于大文件使用分块上传:
$handle = fopen($localFile, 'rb');
$sftp->put($remoteFile, $handle, SFTP::SOURCE_LOCAL_FILE | SFTP::RESUME);
fclose($handle);






