How do I copy or move remote files with phpseclib?
Asked Answered
T

4

5

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/

Tingley answered 5/4, 2016 at 14:49 Comment(0)
S
9
$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".

Sustentacular answered 30/9, 2016 at 16:35 Comment(1)
Don't know why this is downvoted , it is also a option to move files, After successfully moved removed original file. by $sftp->delete('path');Carilyn
P
4

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

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

Pilotage answered 12/11, 2019 at 17:2 Comment(0)
O
1

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));
}
Oneirocritic answered 11/4, 2016 at 20:45 Comment(2)
This creates a local directory and downloads all the files in the remote sftp to the local machine, in thye directory created. Its not what Jan Neuman asked for.Sustentacular
@LawrenceGandhar - Looks like there was a typo. I created a directory but then wasn't writing to the newly created directory. I've updated the code. But do feel free to downvote rather than actually edit and correct in the case of obvious typos!Oneirocritic
G
1

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.
Gilcrest answered 30/1, 2018 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.