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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With