Jan Neuman
Jan Neuman

Reputation: 67

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.

e.g.:

copy all files of

/jn/xml/

to

/jn/xml/backup/

Upvotes: 5

Views: 7269

Answers (4)

Lawrence Gandhar
Lawrence Gandhar

Reputation: 728

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

Upvotes: 9

Maxime
Maxime

Reputation: 61

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

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

Upvotes: 4

hsibboni
hsibboni

Reputation: 463

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.

Upvotes: 1

neubert
neubert

Reputation: 16792

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

Upvotes: 1

Related Questions