1

Currently working on a Symfony 3 application. I created a service that lets users upload an image, then choose a crop section, and finally saves the avatar with a specific height and width. Avatars are saved in the /web/img/uploads/avatar/ folder. I'm using the user id to name the file. So the user with the id 13 will have his avatar saved at /web/img/uploads/avatar/13.png.

My problem is that, when an user updates his avatar, the file is correctly replaced in the folder, but on the actual website the avatar displayed remains the old one for a while. In dev environment this takes something like a few minutes before the new avatar replaces the old one. Even if I go to the avatar url (localhost/app_dev.php/img/uploads/avatar/xxx.png) I still see the old avatar for a while before it's eventually replaced by the new one. Tho, the avatar in the filesystem is instantly replaced, as expected.

I figured this might come from the cache. I tried searching for solutions on google but all I found was related to the LiipImagineBundle and its cache manager, but I'm not using this bundle...

I tried deleting the old avatar if it exists after figuring out its name, and before actually croping and saving the image. As follows.

if(file_exists($dst)) {
    unlink($dst);
}

But it doesn't work. At all.

Any ideas?

Roman
  • 2,530
  • 2
  • 27
  • 50
Kishlin
  • 373
  • 2
  • 15
  • it's just browser cache – bxN5 Mar 02 '17 at 15:29
  • And there's really nothing I can do about it, except telling my users "Hey, you changed your avatar, that's great, now wait for a while until your browser eventually decides to update its cache and you'll see your brand new picture." ? Or just randomize the images' names I guess, so that the url changes since it will get a new one each time the user uploads a new avatar. – Kishlin Mar 02 '17 at 15:33
  • try to send your clients headers (Cache-control: no-cache, must-revalidate) – bxN5 Mar 02 '17 at 15:35
  • here more options http://stackoverflow.com/questions/3137934/how-to-clear-browser-cache-when-re-uploading-image-with-same-filename-in-php – bxN5 Mar 02 '17 at 15:36
  • Use random name for uploaded images and that's it. – malcolm Mar 02 '17 at 17:58

1 Answers1

2

This is definitely browser cache as says bxN5. But I'm not agree with changing headers. If you choose to manage this by modifying cache headers, this will force you to permanently remove the cache on these images or let web browsers ask your server if these images have been modified (fewer downloaded bytes but an additional request at each call).

I think that the better way is to change the image url by changing image name or add query string. In both cases, you need a version identifier for your image. You can use the modification date of the image (timestamp).

Alphonse D.
  • 571
  • 2
  • 5