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

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay