Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents no caching?

I'm using file_get_contents() to load a dynamic image from an external website.

The problem is that the image has been updated on the remote website but my script is still displaying the old image. I assume the server cache the image somewhere but how can i force the server to clear the cache and use the updated image when getting the file with file_get_contents ?

On my local machine, i had to do CTRL+F5 to force refresh on the image.

I also tryed to add no cache header to my script, but it didn't work:

    $image = imagecreatefromstring(file_get_contents($path));
    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date dans le passé
header('Content-type: image/png');
imagepng($image);
exit();
like image 316
libertaire Avatar asked Feb 13 '14 12:02

libertaire


People also ask

Does file_get_contents cache?

The correct answer is yes. All the PHP file system functions do their own caching, and you can use the "realpath_cache_size = 0" directive in PHP.

Is file_get_contents secure?

Unfortunately, file_get_contents() is a dangerous function when used with data obtained from user input, as it is the case. Using it could allow diverse kinds of attacks, from Denial of Service to loading of remote malicious resources.

How does file_get_contents work?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.


1 Answers

Your problem is that you're using external resource to load your file. Once it was loaded - there's no sense to send some headers to your client. Your image already been loaded (and that was cache from external resource).

However, there's easy trick to resolve an issue. Let's suppose you're using something like http://domain.com/path/to/image in your $path. Then just do:

$image = imagecreatefromstring(file_get_contents($path.'?'.mt_rand()));

-so idea is to add some random value to GET-request and prevent it from being cached.

like image 106
Alma Do Avatar answered Oct 01 '22 13:10

Alma Do