Upload files via FTP in Laravel

October 11, 2022 | 2 minute read

Need to manipulate files via FTP with Laravel? Look no further.

Upload files via FTP in Laravel

Getting Started

While we generally reach for cloud storage solutions like AWS S3 and Digital Ocean Spaces to store and serve assets, sometimes you find yourself in a situation where you need to move data via FTP. Fortunately Laravel makes this super easy.

I'm going to assume you have an existing Laravel 9.x project; let's go ahead and install the required dependency to use the FTP Driver:

composer require league/flysystem-ftp "^3.0"

Similarly, you'll install the respective dependency if you plan to use the SFTP driver:

composer require league/flysystem-sftp-v3 "^3.0"

Add a filesystem

Next you'll open filesystems.php and add the following entry within the disks array, replacing the placeholders with your own values. I would recommend creating entries in your .env file for some of these values.

'placeholder_filesystem_name' => [
'driver' => 'ftp',
'host' => 'placeholder_ip_address',
'username' => 'placeholder_username',
'password' => 'placeholder_password',
'root' => '/placeholder_root_folder',
// Optional FTP Settings...
// 'port' => env('FTP_PORT', 21),
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,

There are additional settings options for SFTP connections:

'placeholder_filesystem_name' => [
'driver' => 'sftp',
'host' => 'placeholder_ip_address',
'username' => 'placeholder_username',
'password' => 'placeholder_password",
'root' => '/placeholder_root_folder',
// Settings for SSH key based authentication with encryption password...
// 'privateKey' => env('SFTP_PRIVATE_KEY'),
// 'password' => env('SFTP_PASSWORD'),
// Optional SFTP Settings...
// 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'),
// 'maxTries' => 4,
// 'passphrase' => env('SFTP_PASSPHRASE'),
// 'port' => env('SFTP_PORT', 22),
// 'timeout' => 30,
// 'useAgent' => true,

Put it to Use

Now you're all set to start storing, retrieving and deleting files via (S)FTP.

use Illuminate\Support\Facades\Storage;
// ...
// Get object
$myFile = Storage::disk('placeholder_filesystem_name')->get('fileName.csv');
// Put object
Storage::disk('placeholder_filesystem_name')->put('fileName.csv', $myFile);
// Delete Object