Steevie Steevie - 1 month ago 5x
PHP Question

Prevent browser from caching images

To achieve that unauthenticated users cannot view images just by guessing the URL (e. g.
I store all images outside the public directory and offer a URL that accepts the unique-id of the picture and checks whether the user is authenticated:

// Laravel code behind
public function getimage($uid) {

if(Auth::check()) {

$filename = Picture::findorfail($uid)->filename; // e. g. '123.jpg'
return response()->download(storage_path('images/' . $filename), null, [], null);

} else {

return response()->download('images/no_access.jpg', null, [], null);



Thus, an authenticated user gets the image '123.jpg' and a non-authenticated user gets the image 'no_access.jpg' which is just a red text 'No access' on a white background.

Everything works perfect, as long as I manually hard-clear the cache of my browser (Chrome in my case) after logging out.

But if

  • I login and access the image via
    then I get the image '123.jpg' (correct until here)

  • then logout and call
    once more then I should get the 'no_access.jpg' but because of the browser cache I get the protected image '123.jpg' (cache overrides the authorization check)

I already tried
<meta http-equiv="expires" content="0">
but without any success. Agian, if I hard-clear the cache, everything is perfect - but normal users wouldn't do that.

How do I tell the browser to not cache?

Thanks in advance!


Try putting a random variable on the end of the url{{rand()}}