【发布时间】:2011-06-09 00:57:42
【问题描述】:
我遇到过许多用于 Web FTP 客户端的 PHP 脚本。我需要在 PHP 中将 SFTP 客户端实现为 Web 应用程序。 PHP 是否支持 SFTP?我找不到任何样品。 谁能帮我解决这个问题?
【问题讨论】:
我遇到过许多用于 Web FTP 客户端的 PHP 脚本。我需要在 PHP 中将 SFTP 客户端实现为 Web 应用程序。 PHP 是否支持 SFTP?我找不到任何样品。 谁能帮我解决这个问题?
【问题讨论】:
PHP 具有 ssh2 流包装器(默认禁用),因此您可以通过使用ssh2.sftp:// 协议来将 sftp 连接与支持流包装器的任何函数一起使用,例如
file_get_contents('ssh2.sftp://user:pass@example.com:22/path/to/filename');
或者 - 当也使用ssh2 extension时
$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');
见http://php.net/manual/en/wrappers.ssh2.php
顺便说一句,关于这个话题已经有很多问题了:
【讨论】:
ssh2 的功能不是很好。难以使用且难以安装,使用它们将保证您的代码具有零可移植性。我的建议是使用phpseclib, a pure PHP SFTP implementation。
【讨论】:
我发现“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);
【讨论】:
安装 Flysystem v1:
composer require league/flysystem-sftp
那么:
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
....
阅读:
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
那么:
//$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);
【讨论】:
我进行了一次全面的逃避,并编写了一个创建批处理文件的类,然后通过system 调用调用sftp。不是最好(或最快)的方法,但它可以满足我的需要,并且不需要在 PHP 中安装任何额外的库或扩展。
如果您不想使用 ssh2 扩展,这可能是您的选择