Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure an SCP/SFTP file storage?

My Laravel application should copy files to another remote host. The remote host is accessible only via SCP with a private key. I would like to configure a new file storage (similarly as FTP), but I have found no information, how to define an SCP driver.

like image 208
Antonín Slejška Avatar asked Sep 26 '17 14:09

Antonín Slejška


1 Answers

You'll need to install the SFTP driver for Flysystem, the library Laravel uses for its filesystem services:

composer require league/flysystem-sftp

Here's an example configuration that you can tweak. Add to the disks array in config/filesystems.php:

'sftp' => [
    'driver' => 'sftp',
    'host' => 'example.com',
    'port' => 21,
    'username' => 'username',
    'password' => 'password',
    'privateKey' => 'path/to/or/contents/of/privatekey',
    'root' => '/path/to/root',
    'timeout' => 10,
]

Extend Laravel's filesystem with the new driver by adding the following code to the boot() method of AppServiceProvider (or other appropriate service provider):

use Storage;
use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;
...
public function boot()
{
    Storage::extend('sftp', function ($app, $config) {
        return new Filesystem(new SftpAdapter($config));
    });
}

Then you can use Laravel's API as you would for the local filesystem:

Storage::disk('sftp')->put('path/filename.txt', $fileContents);
like image 160
Cy Rossignol Avatar answered Sep 23 '22 17:09

Cy Rossignol