How to upload a local file to a FTP with Laravel

Posted on March 8, 2018

Today, I had to do a small task at work: upload a file generated by my application to a customer FTP.

As I never did that before in Laravel, I first thought it will be a little bit painful.

Hopefully, Laravel saved my back once again ! Basically, I only had to setup a custom disk with the ftp driver in my config:

// config/filesystems.php

return [
    ...
		
    'disks' => [

        'custom-ftp' => [
				
            'driver' => 'ftp',
						
            'host' => 'ftp.example.com',
						
            'username' => 'myusername',
						
            'password' => 'mypassword',

            // Optional FTP Settings...
            // 'port'     => 21,
            // 'root' => '/Example',
            // 'passive'  => true,
            // 'ssl'      => true,
            // 'timeout'  => 30,
        ],
    ],

];

Then, anywhere I want to upload a file:

use File;
use Illuminate\Support\Facades\Storage;

$localFile = File::get('path/to/local-file.ext');

Storage::disk('custom-ftp')->put('path/to/distant-file.ext', $localFile);

Done ! Did I already talk about my love of Laravel ?