PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to force browser to cache on-demand generated images?

 October 10, 2022     caching, gd, php     No comments   

Issue

An URL such as http://mydomain.com/text/SGVsbG8gd29ybGQh/params/Y29sb3I9I2Y5NzMwNixmb250LWZhbWlseT1Db21pYyBTYW5zLGZvbnQtc2l6ZT0yMnB4LGZvbnQtd2VpZ2h0PWJvbGQsZm9udC1zdHlsZT1ub3JtYWwsdGV4dC1kZWNvcmF0aW9uPW5vbmUsdGV4dC1hbGlnbj1sZWZ0/96 calls on a PHP script that generates an image based on the encoded information contained within the URL. The information encode is the actual text, plus some formatting options (e.g. color, font-weight etc.).

The first time this URL is called, the image is generated, saved to disk and then returned as the response. Starting with the second call to the same URL, the image is loaded from disk and output to the client instead of being generated all over again.

How can I force the browser to treat such a URL as any other path to a stored image file and cache it, so that the next time the URL is called, the browser will load the image from its cache?

Btw, the code I have in the controller (CodeIgniter-based) is as follows:

public function addText($text, $params, $resolution=96) {
        $this->load->model("textimage_model");
        $image = $this->textimage_model->getImage($text, $params, $resolution);

        // Prepare the response headers and output the image to the client
        header("Content-type: image/png");
        header("Content-disposition: inline; filename=mytext.png");

        if (is_string($image)) {
            readfile($image);
        } elseif (is_resource($image)) {
            imagepng($image);
            imagedestroy($image);
        } else {
            //
        }

    }

Solution

Send caching headers.

$seconds_to_cache = 60 * 60 * 24; // 1 day
header("Pragma: cache");
header("Cache-Control: max-age=" . $seconds_to_cache);

Since your caching mechanism seems to be a fingerprint you can have the browser cache it forever.



Answered By - Halcyon
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing