Viewed   80 times

I'm totally new to how to cache images.

I output all images in a gallery with PHP, and want the images already shown, to be cached by the browser, so the PHP script don't have to output the same image again. All I want is the images to show up faster.

When calling an image I do like this:

<img src="showImage.php?id=601">

and the showImage.php-file does:

$id = (int) $_GET['id'];
$resultat = mysql_query("
    SELECT filename, id
    FROM Media 
    WHERE id = $id
$data = mysql_fetch_assoc($resultat);


//Only if the user are logged in
    header("Content-Type: image/jpeg");

    //$data['filename'] can be = dsSGKLMsgKkD3325J.jpg



If you are using php to check if the user is logged in before outputting the message, then you don't want the browser to cache the image.

The entire point of caching is to call the server once and then never call it again. If the browser caches the image, it won't call the server and your script won't run. Instead, the browser will pull your image from cache and display it, even if the user is no longer logged in. This could potentially be a very big security hole.

Sunday, August 7, 2022

try with this code

$temp = $_FILES["file"]["tmp_name"];
$image = basename($_FILES["file"]["name"]);
$img = "images/".$image;
move_uploaded_file($temp, $img);
echo "<img src=images/".$image' />";
Tuesday, August 2, 2022

Ok, sorry, I was thinking too fast :)

imagepng() will output raw data stream directly to the browser, so you must use ob_start() and other output buffering handles to obtain it.

Here you are:

$output = ob_get_contents();

That is - you need to use $output variable for you base64_encode() function.

Saturday, October 29, 2022

This works in all browsers:

window.location.href = '...';

If you wanted to change the page without it reflecting in the browser back history, you can do:

Sunday, November 6, 2022

Code snippet below will invalidate cache entry of the page with URI equal to uriOfCachedPage:

var xhr = new XMLHttpRequest();"GET", uriOfCachedPage, true);
xhr.setRequestHeader("Cache-Control", "max-age=0");

You need to inject this code to script or HTML page that your users will probably get.

For more information check XMLHttpRequest page on MDN and Request Cache-Control Directives section in RFC 7232 Hypertext Transfer Protocol (HTTP/1.1): Caching.

You also can store cachedPageReloaded flag in cookies or localStorage and invalidate cache entry only if it wasn't invalidated before. Check Document.cookie and Window.localStorage pages on MDN.

Saturday, September 10, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :