Laravel: Download files to storage from SFTP

0
13

This post will discuss using Laravel to read and download files from a remote server via SFTP.
For this purpose, we use a third-party package to connect to sftp and download the files to the storage folder in Laravel.

Install league/flysystem-sftp via composer

The first and most important step is to install and configure the league/flysystem-sftp in the Laravel installation.

Run the below command in your project root directory

composer require league/flysystem-sftp "~1.0"

FTP Driver Configuration

Laravel’s file system integration works great with sftp. However, there is no sample configuration listed in the config/filesystems.php file as it does for s3 and other methods.

Use the below to configure the sftp in your Laravel application

'disks' => [
    ........
    .........
    .........
    'sftp' => [
        'driver' => 'sftp',
        'host' => env('SFTP_HOST'),
    
        // Settings for basic authentication...
        'username' => env('SFTP_USERNAME'),
        'password' => env('SFTP_PASSWORD'),
    
        // Settings for SSH key based authentication with encryption password...
        'privateKey' => env('SFTP_PRIVATE_KEY'),
        'password' => env('SFTP_PASSWORD'),
    
        // Optional SFTP Settings...
        // 'port' => env('SFTP_PORT', 22),
        // 'root' => env('SFTP_ROOT'),
        // 'timeout' => 30,
    ],
]

Of course, you need to add the respective values ​​to the .env file to get these values.

Download the files from the remote server and store them in a storage folder

$contents = Storage::disk('sftp')->allFiles('/home/tutsplanet/');
foreach ($contents as $content) 
    Storage::disk('local')->put($content, Storage::disk('sftp')->get($content));

This will save the files in the storage/app/

Hope you were able to follow the tutorial and wish you all the luck in the successful integration of sftp in a Laravel project.


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here