我正在创建PHP页面,我从SFTP服务器下载.CSV文件

时间:2015-03-26 12:27:28

标签: php ftp sftp ssh2-sftp

我想从SFTP下载文件,所以我创建了一个看起来像它的页面。

 <?php
     $username = "XYZ";
     $password = "ABC";
     $url ='FTP.abc.COM';
     // Make our connection
     $connection = ssh2_connect($url);
     // Authenticate
     if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
    // Create our SFTP resource
    if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');

   $localDir  = '/path/to/your/local/dir';
   $remoteDir = '/path/to/your/remote/dir';

   // download all the files
   $files    = scandir('ssh2.sftp://' . $sftp . $remoteDir);
   if (!empty($files))
    {
     foreach ($files as $file) {
        if ($file != '.' && $file != '..')
        {
           ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
        }
    }
}
?>

当我从浏览器调用此页面时。它会显示错误。

Fatal error: Call to undefined function ssh2_connect() in page.php on line 6

如果此方法正确,那么我应该在此页面中编辑什么? 如果有另一种方法,那么建议我这种方法。提前谢谢。

2 个答案:

答案 0 :(得分:1)

phpseclib, a pure PHP SFTP implementation你可能会取得更好的成功。例如

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}

// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
// copies filename.remote to filename.local from the SFTP server
$sftp->get('filename.remote', 'filename.local');
?>

它比libssh2具有许多优点:

http://phpseclib.sourceforge.net/ssh/compare.html

答案 1 :(得分:0)

SSH2函数不是PHP中的标准函数。你必须先安装它们。有关详细信息,请参阅http://php.net/manual/en/ref.ssh2.php

相关问题