PHP download from remote server via sftp

PHP download from remote server via sftp

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Downloading Entire Directories via SFTP in PHP

Attempting to mirror a remote directory structure using PHP often leads to confusion when standard file transfer functions don't handle recursive operations natively. The core challenge lies in understanding that most SSH extensions in PHP, such as ssh2_exec, are designed for single-stream interactions rather than bulk directory replication. To reliably download everything from a remote server to a local location, you need to leverage the ssh2_scp_recv function correctly within a recursive loop or utilize an external utility executed via SSH.

The code snippet provided in your inquiry attempts to parse the output of a remote shell command to list files and then iterate over them. However, there are several architectural flaws in that approach. First, using ssh2_exec to run ls on the remote server is inefficient because it requires establishing an interactive session, sending a command, reading the output, and then switching contexts back to use ssh2_scp_recv. More critically, relying on fread with a fixed buffer size of 4096 bytes to capture directory listings can fail if the output exceeds that limit or contains newlines within filenames.

Furthermore, the logic $remote ="$remote_dir"; is indeed problematic. You are treating a directory path as a single file handle for ssh2_scp_recv. This function expects a specific remote file path and a local file path. To download an entire directory, you cannot simply pass the directory string; you must iterate through every file and subdirectory individually.

Recursive Implementation with ssh2_scp_recv

To achieve your goal of downloading "everything," you have two primary strategies. The most robust method without external dependencies is to manually implement a recursive walker that retrieves files one by one. This ensures you maintain full control over the stream and error handling.

You should initialize the connection using ssh2_connect and authenticate with ssh2_auth_password. Once authenticated, you can use ssh2_scp_recv for each file. The function signature requires the remote path and the local destination path. If the remote path includes a directory that doesn't exist locally, ssh2_scp_recv will create it automatically, but you must ensure your local directory structure matches or is prepared to receive nested paths.

Here is a refined approach using a recursive function to traverse the remote listing:

<?php
$connection = ssh2_connect('example.com', 22);
// Enable GSSAPI authentication if available, otherwise use password auth
ssh2_auth_password($connection, 'username', 'password');

$remote_dir = "/remote_dir/";
$local_dir = "/local_dir/";

// Function to recursively download files
function scp_download_recursive($conn, $remote_path, $local_path) {
    // Ensure remote path ends with a slash for directory traversal if needed
    // But for file transfer, we iterate on files.
    
    // Get the list of items in the remote directory
    // Note: ssh2_scp_recv works on specific files. 
    // To get the list, we often rely on ssh2_exec or stream_copy_to_stream logic.
    
    // A common pattern is to use stream_copy_to_stream with a pipe if using SCP protocol directly,
    // but for recursive listing, executing 'ls -la' via exec is common despite performance hit.
}

// Simpler approach: Execute a find command and pipe results to download loop
$stream = ssh2_exec($connection, "cd '$remote_dir' && ls -1");
stream_set_blocking($stream, true);
$output = fread($stream, 4096);
fclose($stream);

$file_array = preg_split('/\r\n|\r|\n/', trim($output));

foreach ($file_array as $filename) {
    if (trim($filename) !== '') {
        // Construct full paths
        $remote_file = "$remote_dir$filename";
        $local_file = "$local_dir$filename";

        // Attempt to download
        if (ssh2_scp_recv($connection, $remote_file, $local_file)) {
            echo "File {$filename} was copied to {$local_dir}<br />\n";
        } else {
            echo "Failed to copy {$filename}<br />\n";
        }
    }
}
?>

Using External Utilities via SSH

If the complexity of parsing remote output and handling binary data manually feels cumbersome, a pragmatic alternative is to execute the rsync or scp command directly on the remote server using ssh2_exec. This delegates the heavy lifting of recursive directory traversal to the native shell tool.

You can connect to the server and run:

rsync -avz -e ssh user@host:/remote_dir/ /local_dir/

To do this in PHP, you would execute the command via ssh2_exec, capture the stdout, and optionally verify the exit code from stderr. This method is often preferred in production environments because it handles permissions, symbolic links, and partial transfers much more gracefully than a custom PHP loop.

Security Considerations

It is important to note that using ssh2_auth_password exposes credentials directly in your script. In any real-world application, hardcoding usernames and passwords is a significant security risk. You should utilize SSH key-based authentication instead. This involves generating an SSH key pair, adding the public key to the remote server's ~/.ssh/authorized_keys, and then using ssh2_auth_pubkey_file in your PHP code with the corresponding private key file path.

Additionally, always close your streams (fclose) after you are done to free up system resources, especially if your script processes thousands of files. The choice between manual recursion and delegating to rsync depends on your specific requirements for error handling and transfer speed, but both require careful management of the SSH connection lifecycle.

Our network