Laravel Framework, PHP & MySQL, Tutorials

Laravel download files from a route

Laravel makes downloading a server file very easy, in this post I'm going to show a way to download files but only let authenticated users. 

First, a route group is used to set up the auth middleware:

Route::group(['middleware' => 'auth'], function () {
Next create a dedicated download route:
Route::get('download', function () {

Collect a request:

$path = request('f');

Detect the file extension

$extension = pathinfo($path, PATHINFO_EXTENSION);

Create a blocked list array, this is a list of all extensions we won't allow to be downloaded.

$blocked = ['php', 'htaccess'];

If the requested file is not in the blocked array then download it.

if (! in_array($extension, $blocked)) {
    //download the file
    return response()->download($path);
}

Putting it all together:

//only logged in users can download
Route::group(['middleware' => 'auth'], function () {
    
    //respond to route /download?f=path
    Route::get('download', function () {

        //get the GET request
        $path = request('f');

        //look at the extension of the file being requested
        $extension = pathinfo($path, PATHINFO_EXTENSION);

        //create an array of items to reject being downloaded
        $blocked = ['php', 'htaccess'];

        //if the requested file is not in the blocked array
        if (! in_array($extension, $blocked)) {
            //download the file
            return response()->download($path);
        }
    });
});

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.