DEV Community

Shaikh Al Amin
Shaikh Al Amin

Posted on

Securing files/images in laravel

If you put a file in public folder it will be accessible to everyone who knows the file name, because nginx/apache rewrite rules used by Laravel only apply to non-existing files, so Laravel won't even be run when accessing an existing file.

So, you still have to put restricted files somewhere out of public folder. Maybe in storage folder, but ultimately it doesn't matter.

And yes, you should just use Response::download.

Make a small FileController:

class FileController extends Controller {
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function getFile($filename)
    {
        return response()- 
                 >download(storage_path($filename), null, [], null);
    }
}
Enter fullscreen mode Exit fullscreen mode

The fourth argument of download() being null prevents the Content-Disposition header being set to attachment. So your browser won't ask you save the file, but just show it.

Then add a route:

Route::get('file/{filename}', 'FileController@getFile')->where('filename', '^[^/]+$');
Enter fullscreen mode Exit fullscreen mode

And that's it. Now, your authenticated users can download files from storage folder (but not its subfolders) by calling http://yoursite.com/file/secret.jpg. Add you can use this URL in src attribute of an image tag.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay