Skip to content
Advertisement

private file handling with laravel

When I store files like pictures, videos or other files, I do not store them in the public folder but in a private folder that is not publicly accessible. Because only certain users should have access to the files.

With the following example function, for example, I load the images and put them into the view… is this the right way or is there a better way that might take less loading time?

How can I output multiple images from a private folder?

public function thumbnailfeedback($uuid)
    {
        $feedbackimage = FeatureRequest::findOrFail($uuid);
        $thumbnail = storage_path($feedbackimage->image_thumbnail);

        return Image::make($thumbnail)->response();
    }

Advertisement

Answer

Yeah, that’s pretty much the only way if you’re storing images in the non-publicly accessible path.

To speed up you could do it via plain PHP (headers + read file):

       header('Content-Type: image/jpeg');
       header('Content-Length: ' . filesize($thumbnail));
       readfile($thumbnail);
       exit;

or if you would like to keep it to Laravel style type code then something like this would do just fine

$headers = [
    'Content-Type' => 'image/jpeg', // if single type if not determine type
    'Content-Length' => filesize($thumbnail),
];
return response()->file($thumbnail, $headers);

You can optimize this with caching headers and any other flavor stuff.

For multiple images, you would have to make separate requests for each image or you have to archive somehow images and send it to the user, but obviously this would not be viewable by the user unless an un-achieved downloaded package.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement