How do I copy or move remote files with phpseclib?

允我心安 提交于 2019-12-19 04:45:13

问题


I've just discovered phpseclib for myself and would like to use it for my bit of code. Somehow I can't find out how I could copy files from one sftp directory into an other sftp directory. Would be great if you could help me out with this.

e.g.:

copy all files of

/jn/xml/

to

/jn/xml/backup/


回答1:


$dir = "/jn/xml/";
$files = $sftp->nlist($dir, true);
foreach($files as $file)
{   
    if ($file == '.' || $file == '..') continue;
    $sftp->put($dir."backup".'/'.$file, $sftp->get($dir.'/'.$file); 
}

This code will copy contents from "/jn/xml/" directory to "/jn/xml/backup".




回答2:


I think this should do what was asked.

I used composer to import phpseclib so this is not exactly the code I tested, but from the other answers, the syntax should be correct.

<?php
include('Net/SFTP.php');
// connection
$sftp = new Net_SFTP('website.com');
if (!$sftp->login('user', 'pass')) {
    exit('bad login');
}
// Use sftp to make an mv
$sftp->exec('mv /jn/xml/* /jn/xml/backup/');

Notes:

  • if any of the directories do not exist, this will fail. do echo $sftp->exec(... to get the errormsg.
  • you will get a warning because /jn/xml/backup/ is inside /jn/xml/, I would advise moving the files to /jn/xml.bak/
  • you could use 'Net/SSH2' class, since you only do a mv, and do not transfer any files. In fact, the exec is a function from the SSH2 class, and SFTP inherits it from SSH2.



回答3:


To be able to move a file correctly with PHPSeclib, you can use

$sftp->rename($old, $new);




回答4:


Try this:

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

$sftp = new Net_SFTP('website.com');
if (!$sftp->login('user', 'pass')) {
    exit('bad login');
}

$sftp->chdir('/jn/xml/');
$files = $sftp->nlist('.', true);
foreach ($files as $file) {
    if ($file == '.' || $file == '..') {
        continue;
    }
    $dir = '/jn/xml/backup/' . dirname($file);
    if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
    }
    file_put_contents($dir . '/' . $file, $sftp->get($file));
}


来源:https://stackoverflow.com/questions/36429787/how-do-i-copy-or-move-remote-files-with-phpseclib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!