Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save belgareth/4e5cccd98f2e98ff54690d44925b6838 to your computer and use it in GitHub Desktop.
Save belgareth/4e5cccd98f2e98ff54690d44925b6838 to your computer and use it in GitHub Desktop.
Tried this code to retrieve the newest files from a server using php/ ssh2. The problem is that it only downloads one file instead of multiple files. Any help would be appreciated .
#!/usr/bin/php
<?php
$username = "username";
$password = "passwor";
$url = 'adress';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
{echo('Unable to connect.');}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
{echo ('Unable to create SFTP connection.');}
$localDir = 'file:///home/xxx/Downloads/newfile';
$remoteDir = '/home/xxx/Dropbox/dbs';
// download all the files
$dir = ('ssh2.sftp://' . $sftp . $remoteDir);
$numberOfFiles = 2;
$pattern = '/\.(aes|AES)$/'; // check only file with these ext.
$newstamp = 2;
$newname = "";
if ($handle = opendir($dir)) {
while (false !== ($fname = readdir($handle))) {
// Eliminate current directory, parent directory
if (preg_match('/^\.{1,2}$/',$fname)) continue;
// Eliminate other pages not in pattern
if (! preg_match($pattern,$fname)) continue;
$timedat = filemtime("$dir/$fname");
$fils[$fname] = $timedat;
if ($timedat > $newstamp) {
$newstamp = $timedat;
$newname = $fname;
}
}
}
closedir ($handle);
arsort ($fils, SORT_NUMERIC);
sfor($i = 0; $i < $numberOfFiles ; $i++)
$fils2 = array_keys($fils);
$i = 0;
foreach($fils2 as $s){
$i++;
echo "$i " . $s . "<br>\n";
if($i == $numberOfFiles )break;
}
// $newstamp is the time for the latest file
// $newname is the name of the latest file
// print last mod.file - format date as you like
$rttp = ssh2_scp_recv($connection, "$remoteDir/$newname", "$localDir/$newname")
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment