如何使用PHP进行SFTP?

ind*_*ama 79 php sftp

我遇到过很多用于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

另外,关于这个话题还有很多问题:

  • 即使使用file_get_contents(),您仍然需要ssh2扩展名(afaik). (3认同)
  • @DavidSpector 仅取决于服务器的设置。即使使用 SFTP/SSH,您也可以拥有常规的 USER/PASS 组合。 (3认同)

小智 38

ssh2功能不是很好.难以使用和更难安装,使用它们将保证您的代码具有零可移植性.我的建议是使用纯PHP PHP SFTP实现的phpseclib.

  • @indranama您是否将此标记为正确答案,以便将来的用户不必阅读评论即可找到最适合您的评论? (3认同)

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)

  • git仓库在这里:https://github.com/phpseclib/phpseclib/tree/master/phpseclib (2认同)
  • 您可以更新 phpseclib 2.0 的答案吗?您当前的示例已过时。 (2认同)

Sal*_*nes 6

安装 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)

  • @Wanjia 在 StackOverflow,我认为我们是用时间来驱动的。因此,最好保持答案的更新。 (2认同)