Laravel - How to upload file to FTP server?

Learn how to upload files to an FTP server in Laravel. This article will show how to config the FTP server to Laravel filesystem and upload the file via the Laravel filesystem to the FTP server.

Config FTP driver

In the ./config/filesystems.php

<?php

return [
    'default' => env('FILESYSTEM_DRIVER', 'local'),
    'disks' => [
        'ftp' => [
            'driver' => 'ftp',
            'host' => env('FTP_HOST'),
            'username' => env('FTP_USERNAME'),
            'password' => env('FTP_PASSWORD'),
            'port'     => env('FTP_PORT'),
            'root' => env('FTP_ROOT'),
            'ssl'      => env('FTP_SSL', false),
            'timeout'  => env('FTP_TIMEOUT', 30)
        ]
    ],
    'links' => [
        public_path('storage') => storage_path('app/public'),
    ],
];

In the .env

Config your FTP server

FTP_HOST='ftp.dlptest.com' # online ftp server for test 
FTP_USERNAME='dlpuser'
FTP_PASSWORD='rNrKYTX9g7z3RgJRmxWuGHbeu'
FTP_PORT=21
FTP_ROOT='/'

Implementation

In the controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FtpController extends Controller
{
    public function uploadToFtp(Request $request)
    {
        Storage::disk('ftp')->put('/', $request->file);
        return $request->file;
    }
}

In the ./routes/api.php

<?php

use App\Http\Controllers\FtpController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('ftp/upload', [FtpController::class, 'uploadToFtp']);

Upload via API testing tool

Check the FTP server

You can test the FTP server through the FileZilla tool. Or test it with the command line.

ftp ftp.dlptest.com

It will prompt you to enter a username and password then you will have access to the FTP server via the command line.