Caves Travel Diving Graphics Mizar Texts Cuisine Lemkov Contact Map RSS Polski
Trybiks' Dive Texts PHP Turning Browser Caching off when Displaying Images Using PHP YAC Software
  Back

List

Charsets

Charts

DBExpress

Delphi

HTML

Intraweb

MSTest

PHP

Programming

R

Rhino Mocks

Software

Testing

UI Testing

VB.NET

VCL

WPF

Turning Browser Caching off when Displaying Images Using PHP
Ok, so the standard PHP script for showing images goes something like this:
  <?php
    require_once( 'db.php' );
    $id = $_GET['id'];
    if( check_input( $id ) )
    {
      if( $con = get_connection() )
      {
        $result = mysql_query( "select * from IMAGES where ID = '$ID'" );
        if( $row = mysql_fetch_array( $result ) )
        {
          header( "Content-type: {$row['MIME']}" );
          echo $row['IMAGE'];
        }
        mysql_close( $con );
      }
    }
  ?>
Let's assume that check_input() checks whether the ID passed to the script is a valid image ID (and doesn't include, for instance, any SQL code that might exploit our query here).

Another note is that this script displays an image from a database. As far as browser caching is concerned, it doesn't matter whether the image comes from a file or from other sources.

The idea here is that if this script is saved in a file view_image.php, for example, it can be later called in HTML pages like this:
  <img src="view_image.php?id=photo" />
If an image in updated (be it in a DB or a file) and then the page showing that image is refreshed, the browser may display the previous image (and not the new image) if its caching is configured that way.

One solution is to change the browser's configuration. But we don't want to force our users to do that just to be able to use our site! So, another possibility is to change caching just for this image. This can be accomplished by adding just one line to the script above:
  header( "Cache-control: no-cache" );
This is how the whole script would look like now:
  <?php
    require_once( 'db.php' );
    $id = $_GET['id'];
    if( check_input( $id ) )
    {
      if( $con = get_connection() )
      {
        $result = mysql_query( "select * from IMAGES where ID = '$ID'" );
        if( $row = mysql_fetch_array( $result ) )
        {
          header( "Cache-control: no-cache" );
          header( "Content-type: {$row['MIME']}" );
          echo $row['IMAGE'];
        }
        mysql_close( $con );
      }
    }
  ?>
Note that turning off caching for all images may degrade performance (especially over slow connections for pages with lots of images).

HTH

Top

Comments
Alas!
No comments yet...

Top

Add a comment (fields with an asterisk are required)
Name / nick *
Mail (will remain hidden) *
Your website
Comment (no tags) *
Enter the text displayed below *
 

Top

Tags

PHP


Related pages

PHP's mail()