How to force a web browser NOT to cache images

后端 未结 17 837
太阳男子
太阳男子 2020-11-22 13:51

Background

I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML

17条回答
  •  攒了一身酷
    2020-11-22 14:45

    You may write a proxy script for serving images - that's a bit more of work though. Something likes this:

    HTML:

    
    

    Script:

    // PHP
    if( isset( $_GET['img'] ) && is_file( IMG_PATH . $_GET['img'] ) ) {
    
      // read contents
      $f = open( IMG_PATH . $_GET['img'] );
      $img = $f.read();
      $f.close();
    
      // no-cache headers - complete set
      // these copied from [php.net/header][1], tested myself - works
      header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Some time in the past
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
      header("Cache-Control: no-store, no-cache, must-revalidate"); 
      header("Cache-Control: post-check=0, pre-check=0", false); 
      header("Pragma: no-cache"); 
    
      // image related headers
      header('Accept-Ranges: bytes');
      header('Content-Length: '.strlen( $img )); // How many bytes we're going to send
      header('Content-Type: image/jpeg'); // or image/png etc
    
      // actual image
      echo $img;
      exit();
    }
    

    Actually either no-cache headers or random number at image src should be sufficient, but since we want to be bullet proof..

提交回复
热议问题