Posted by Arjun on Tuesday 7th March 2017

Laravel download files via FTP

How to Laravel 5.x laravel 5.3 FTP connnection FTP

This post is going to be about downloading files from the remote server via FTP mechanism in your Laravel application.

Let's create a controller called DownloadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Response;

class DownloadController extends Controller
{
     function downloadFile(Request $request) {

        $file = $request->get('file');
        if(!$file) {
            return Response::json('please provide valid path', 400);
        }
        $fileName = basename($file);

         $ftp = Storage::createFtpDriver([
                        'host'     => 'your_host',
                        'username' => 'your_ftp_user',
                        'password' => 'your_ftp_user_password',
                        'port'     => '21', // your ftp port
                        'timeout'  => '30', // timeout setting 
          ]); 

           $filecontent = $ftp->get($file); // read file content 
           // download file.
           return Response::make($filecontent, '200', array(
                'Content-Type' => 'application/octet-stream',
                'Content-Disposition' => 'attachment; filename="'.$fileName.'"'
            ));
    }
}

Now let's inform about this controller to routes/web.php

   Route::get('downloadFile','[email protected]');    

That's it. Now point your browser to http://yourhost.com/downloadFile?file=remote_path/fileName.png.