2011-01-14 86 views
58

我遇到了很多用於Web FTP客戶端的PHP腳本。我需要在PHP中將SFTP客戶端實現爲Web應用程序。 PHP支持SFTP嗎?我找不到樣品。 任何人都可以幫助我嗎?如何使用PHP的SFTP?

回答

57

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

31

的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

0

我執行了一個完整的cop-out,寫了一個類創建一個批處理文件,然後通過調用system調用sftp。不是最好的(或最快)的方法,但它適用於我所需要的,它不需要在PHP中安裝額外的庫或擴展。

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

+0

相關線索,幫助我:https://groups.google.com/forum/#!topic/comp.security.ssh/_55TdDdUTCw – Quamis 2015-02-24 17:23:28

22

我發現,「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); 
-1

Monsta FTP通過一個基於Web的客戶端是免費的下載提供SFTP/SCP以及正常的FTP。 (免責聲明:我參與這個項目)