我遇到过很多用于Web FTP客户端的PHP脚本.我需要在PHP中将SFTP客户端实现为Web应用程序.PHP是否支持SFTP?我找不到样品.谁能帮我这个?
Gor*_*don 69
PHP具有ssh2流包装器(默认情况下禁用),因此您可以通过使用ssh2.sftp://
for协议将sftp连接与支持流包装器的任何功能一起使用,例如
file_get_contents('ssh2.sftp://user:pass@example.com:22/path/to/filename');
Run Code Online (Sandbox Code Playgroud)
或 - 当还使用ssh2扩展名时
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
Run Code Online (Sandbox Code Playgroud)
见http://php.net/manual/en/wrappers.ssh2.php
另外,关于这个话题还有很多问题:
小智 38
ssh2功能不是很好.难以使用和更难安装,使用它们将保证您的代码具有零可移植性.我的建议是使用纯PHP PHP SFTP实现的phpseclib.
Pru*_*wee 28
我发现"phpseclib"可以帮助你(SFTP和更多功能).http://phpseclib.sourceforge.net/
要将文件放入服务器,只需调用(来自http://phpseclib.sourceforge.net/sftp/examples.html#put的代码示例)
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);
Run Code Online (Sandbox Code Playgroud)
安装 Flysystem v1:
composer require league/flysystem-sftp
Run Code Online (Sandbox Code Playgroud)
然后:
use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;
$filesystem = new Filesystem(new SftpAdapter([
'host' => 'example.com',
'port' => 22,
'username' => 'username',
'password' => 'password',
'privateKey' => 'path/to/or/contents/of/privatekey',
'root' => '/path/to/root',
'timeout' => 10,
]));
$filesystem->listFiles($path); // get file lists
$filesystem->read($path_to_file); // grab file
$filesystem->put($path); // upload file
....
Run Code Online (Sandbox Code Playgroud)
读:
https://flysystem.thephpleague.com/v1/docs/
升级到v2:
https://flysystem.thephpleague.com/v2/docs/advanced/upgrade-to-2.0.0/
安装
composer require league/flysystem-sftp:^2.0
Run Code Online (Sandbox Code Playgroud)
然后:
//$filesystem->listFiles($path); // get file lists
$allFiles = $filesystem->listContents($path)
->filter(fn (StorageAttributes $attributes) => $attributes->isFile());
$filesystem->read($path_to_file); // grab file
//$filesystem->put($path); // upload file
$filesystem->write($path);
Run Code Online (Sandbox Code Playgroud)