Search code examples
phpcachinglaravel-5metaphp-5.6

Prevent browser from caching images


To achieve that unauthenticated users cannot view images just by guessing the URL (e. g. http://www.test.com/images/123.jpg 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 http://www.test.com/image/5
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 http://www.test.com/image/5 then I get the image '123.jpg' (correct until here)
  • then logout and call http://www.test.com/image/5 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!


Solution

  • Try putting a random variable on the end of the url

    http://www.test.com/images/123.jpg?{{rand()}}