通过SFTP从远程服务器下载PHP文件

7

可能以前已经有人问过了,我是PHP新手,正在尽力学习,但这真的让我困惑。

基本上我想知道的是,如何使用PHP代码将所有内容从远程服务器下载到本地位置。 我卡在了下载所有内容而不仅仅是一个文件上。所以请问有人能向我展示/解释如何做到这一点吗?

目前我所拥有的:

<?php
$connection - ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$remote_dir="/remote_dir/";
$local_dir="/local_dir/";

$remote ="$remote_dir";
$stream = ssh2_exec($connection, $remote);
stream_set_blocking($stream,true);
$command=fread($stream,4096);

$array=explode(\n,$command);

$total_files=sizeof($array);

for($i=0;$i<$total_files;$i+++){
    $file_name=trim($array[$i]);
    if($file_name!=''{
        $remote_file=$remote_dir.$file_name;
        $local_file=$local_dir.$file_name;

        if(ssh2_scp_recv($connection, $remote_file,$local_file)){
            echo "File ".$file_name." was copied to $local_dir<br />"; 
        }
    }
}
fclose($stream);
?>

我认为我的 $remote ="$remote_dir"; 是有问题的,说实话当我想要整个目录时,我得到了 $filename。这是我目前拥有的全部内容。


3
请发布您已经完成的内容,并在需要时替换任何敏感信息。 - Prix
刚刚添加了我目前拥有的内容。就像我说的,我不知道它是否正确,我只是几周前才开始学习PHP,但我可能在这里有些超纲了。 - user2589167
已经发布了一个示例,希望你喜欢,因为你是 Stackoverflow 的新成员。[我还建议你参观一下 Stackoverflow 引导,以了解如何最好地使用这个网站,这将极大地帮助你未来的提问。](http://stackoverflow.com/about) - Prix
3个回答

27
这里是关于如何读取文件夹并下载其中所有文件的简短代码:
<?php
$host = 'localhost';
$port = 22;
$username = 'username';
$password = 'password';
$remoteDir = '/must/be/the/complete/folder/path';
$localDir = '/can/be/the/relative/or/absolute/local/path';

if (!function_exists("ssh2_connect"))
    die('Function ssh2_connect not found, you cannot use ssh2 here');

if (!$connection = ssh2_connect($host, $port))
    die('Unable to connect');

if (!ssh2_auth_password($connection, $username, $password))
    die('Unable to authenticate.');

if (!$stream = ssh2_sftp($connection))
    die('Unable to create a stream.');

if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
    die('Could not open the directory');

$files = array();
while (false !== ($file = readdir($dir)))
{
    if ($file == "." || $file == "..")
        continue;
    $files[] = $file;
}

foreach ($files as $file)
{
    echo "Copying file: $file\n";
    if (!$remote = @fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}", 'r'))
    {
        echo "Unable to open remote file: $file\n";
        continue;
    }

    if (!$local = @fopen($localDir . $file, 'w'))
    {
        echo "Unable to create local file: $file\n";
        continue;
    }

    $read = 0;
    $filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}");
    while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
    {
        $read += strlen($buffer);
        if (fwrite($local, $buffer) === FALSE)
        {
            echo "Unable to write to local file: $file\n";
            break;
        }
    }
    fclose($local);
    fclose($remote);
}

您还可以恢复此代码以 (它不会复制目录)
while (false !== ($file = readdir($dirHandle)))
{
    if ($file == "." || $file == "..")
        continue;

    echo "Copying file: $file\n";
    if(!ssh2_scp_recv($connection, $remoteDir . $file, $localDir . $file))
        echo "Could not download: ", $remoteDir, $file, "\n";
}

如果您在远程文件夹上没有使用完整路径,它将不起作用。
opendir("ssh2.sftp://{$stream}{$remoteDir}")

好吧,看起来我离正确的答案还有很远的距离,感谢你。 - user2589167
1
如果(!$remote = @fopen("ssh2.sftp://{$stream}/{$remoteDir}/{$file}", 'r')) //注意斜杠 - jj-aa

0
更新:我很友善地被纠正,这不是使用sftp,而是使用ftps。 这里有一个Stackoverflow链接讨论 使用PHP进行SFTPPHP文档已经涵盖了大多数你需要的内容。 这是获取远程目录中内容列表的示例:
<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

$buff = ftp_rawlist($conn_id, '.');
 var_dump($buff);
ftp_close($conn_id); 
?> 

谢谢您的快速回复!所以使用这个,我可以检查目录中的所有内容,并且使用ftp_ssl与使用SFTP相同吗? - user2589167
是的。这将为您提供目录中所有文件的列表,并且您正在使用SSL,即SFTP。 - Arth Du
3
不,它们不是同一件事,SFTP是SSH文件传输协议,而FTP over SSL也称为FTP安全和FTP-SSL。这是一篇很好的文章https://www.eldos.com/security/articles/4672.php。 - Prix
你和我一样,感谢帮助,那么我将使用诸如ssh_等工具? - user2589167
我更新了我的答案,并附上了另一个关于使用PHP进行SFTP的SO讨论链接。 - Arth Du

0

在这里,您将找到使用PHP进行SFTP操作的所有示例。 http://phpseclib.sourceforge.net/sftp/examples.html

<?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');
?>

我认为OP要求纯PHP函数,而不是使用phpseclib。 - le hien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接