简体   繁体   中英

How do I copy or move remote files with phpseclib?

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.

eg:

copy all files of

/jn/xml/

to

/jn/xml/backup/

$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".

为了能够使用 PHPSeclib 正确移动文件,您可以使用

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

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));
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM