php使用sftp上传文件

时间:2023-12-19 14:16:44

搞这个SFTP文件传输搞了一整天真是醉了,从sftp安装,到php的ssh2扩展安装,最后到php应用ssh2来上传文件;最后就没有最后了

Failure creating remote file: (null)  一直报这个错误!网上能搜的基本找了个遍都不起作用,一开始以为laravel框架问题,后来写成原生php脚本也是这个错误,Fine!很好真的没辙了;

解决方法:

使用 league/flysystem-sftp 这个而插件来运行SFTP文件传输,在composer下载依赖使用;使用方法也很简单

use League\Flysystem\Sftp\SftpAdapter;
use League\Flysystem\Filesystem; $adapter = new SftpAdapter([
'host' => 'example.com',
'port' => 22,
'username' => 'username',
'password' => 'password',
'privateKey' => 'path/to/or/contents/of/privatekey',
'root' => '/path/to/root',
'timeout' => 10,
'directoryPerm' => 0755
]); $filesystem = new Filesystem($adapter);
//获取到对象之后
1. $filesystem->put('远程文件路径','内容');
2. $filesystem->putstream('远程文件路径','文件句柄');//通过fopen获取句柄

个人备忘:
linux/ubuntu系统中安装了ssh会自带sftp,如果没有配置的话会一直连接不上远程
Unable to negotiate with 113.105.66.197 port 8521: no matching host key type found. Their offer: ssh-dss
Couldn't read packet: Connection reset by peer
解决方法:
在/个人目录/.ssh/下面 添加config文件
vi /个人目录/.ssh/config
HostkeyAlgorithms +ssh-dss 添加这段话保存退出,在连接一下SFTP试试