Skip to content

Instantly share code, notes, and snippets.

@danielbwa
Last active November 16, 2022 09:38
Show Gist options
  • Save danielbwa/6993444 to your computer and use it in GitHub Desktop.
Save danielbwa/6993444 to your computer and use it in GitHub Desktop.
List and download all files in a directory through sftp with php / ssh2. In my example i use scandir to list the files and ssh2_scp_recv to grab a file. I've found a lot of examples using fopen to grab the remote file, that didn't work for me and i found the code below cleaner than the fopen option. For an example on how to do the same as my exa…
<?php
$username = "your_username";
$password = "your_pass";
$url = 'your_stp_server_url';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
?>
@belgareth
Copy link

Can this be modified to download a X number of files instead of all the files???

@danielbwa
Copy link
Author

danielbwa commented Jul 25, 2017

@belgareth That should be easy to do, not sure why you want to do that but keep a count in the foreach and break out of the foreach with break; when your desired number of download has been reached. http://php.net/manual/en/control-structures.break.php

@1manfactory
Copy link

Just what I needed. A remote download via SSH

@g9rga
Copy link

g9rga commented Jul 19, 2021

Suddenly, it doesn't work for files with tab in the name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment