Open menu

Learn

How to use SFTP as a Laravel Filesystem

In this article, we will explore how to use SFTP as a Laravel filesystem, allowing you to manage files with ease. Whether you're new to Laravel or an experienced developer, this guide will provide you with everything you need to know about using SFTP as a Laravel filesystem.

Install flysystem-sftp-v3

Laravel provides a powerful abstraction layer for working with files. It supports several file storage systems out of the box and can be easily extended. To use SFTP as a Laravel Filesystem, we need to create a custom driver that uses the league/flysystem-sftp-v3 package. Flysystem is a filesystem abstraction library for PHP that provides a simple and unified API for working with files across different storage systems.
composer require league/flysystem-sftp-v3

Add a new SFTP driver

Now that flysystem-sftp-v3 was installed, it's time to configure the new disk in the Laravel filesystems config file. Open the config/filesystems.php file and add the new SFTP disk:
'disks' => [
    // ... other disks here
    'sftp' => [
        'driver' => 'sftp',
        'host' => env('SFTP_HOST'),
        'port' => env('SFTP_PORT', 22),
        'username' => env('SFTP_USERNAME'),
        'password' => env('SFTP_PASSWORD'),
        'root' => env('SFTP_ROOT'),
        'permPublic' => 0755,
        'directoryPerm' => 0755,
        'visibility' => 'public',
        'timeout' => 30,
    ],
]
Now open your .env file and add the credentials of the SFTP server you want to use.
SFTP_HOST=eu-central-1.sftpcloud.io # Replace with the host of your SFTP server
SFTP_USERNAME="sftpcloud-user" # The name of your SFTP user
SFTP_PASSWORD="sftpcloud-pass" # The password of your SFTP user
SFTP_PORT=22 # If your server is not using the default port, replace it
SFTP_ROOT="/" # Root directory on the SFTP server where the files will be stored

Use the SFTP disk

That's it. Now you are able to use the SFTP server as a normal Laravel filesystem.
// List all the files
Storage::disk('sftp')->list();

// Delete a directory
Storage::disk('sftp')->deleteDirectory('my-directory');

// Write to a file
Storage::disk('sftp')->put('example.txt', 'My content');

// Create a directory
Storage::disk('sftp')->makeDirectory('my-directory');

Conclusion

In this article, we covered the steps required to set up an SFTP filesystem in Laravel. By leveraging the power of Laravel's filesystem abstraction layer and the league/flysystem-sftp-v3 package, we are able to use an SFTP server as a native Laravel disk.