如何使用PHP的SFTP?

问题描述:

我遇到了很多用于Web FTP客户端的PHP脚本。我需要在PHP中将SFTP客户端实现为Web应用程序。 PHP支持SFTP吗?我找不到样品。 任何人都可以帮助我吗?如何使用PHP的SFTP?

PHP有ssh2流包装器(默认禁用),因此您可以通过使用ssh2.sftp://的协议来使用任何支持流包装器的函数的sftp连接。

file_get_contents('ssh2.sftp://user:[email protected]: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

在一个侧面说明,也有相当大量关于这个话题已经问题:

+0

的file_get_contents和file_put_contents两个工作真棒。从来不知道他们使用sftp,并且比使用内置sftp的东西容易得多。谢谢! – jbrahy 2015-03-11 22:53:49

+0

即使在使用file_get_contents()时,您仍然需要ssh2扩展名(afaik)。 – StanE 2016-01-26 05:28:51

的SSH2功能不是很好。使用起来难以使用且难以安装,使用它们可以保证您的代码具有零可移植性。我的建议是使用phpseclib, a pure PHP SFTP implementation

+0

只支持SFTP V3 – Blacksonic 2013-05-29 14:07:39

+0

@indranama你将标志着这是正确的答案,以便未来的用户不必阅读评论找到这对你最有效? – 2017-06-30 14:14:45

我执行了一个完整的cop-out,写了一个类创建一个批处理文件,然后通过调用system调用sftp。不是最好的(或最快)的方法,但它适用于我所需要的,它不需要在PHP中安装额外的库或扩展。

可能是要走的路,如果你不希望使用ssh2扩展

+0

相关线索,帮助我:https://groups.google.com/forum/#!topic/comp.security.ssh/_55TdDdUTCw – Quamis 2015-02-24 17:23: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); 

如果你可以使用SSH2扩展PHP我建议检查了这一点:

idct SFTP client on GitHub

Monsta FTP通过一个基于Web的客户端是免费的下载提供SFTP/SCP以及正常的FTP。 (免责声明:我参与这个项目)