在php脚本上缓存图像

在php脚本上缓存图像,php,image,caching,random,browser-cache,Php,Image,Caching,Random,Browser Cache,我使用的是这段很棒的随机数发生器代码:,但是图像不会保存在浏览器的缓存中,这意味着每当站点重新加载时,图像都会刷新 是否可以将图像缓存在以下代码中? 我使用此脚本的原因是,出于某种原因,css上的php解析无法在我的服务器上工作 <?php $folder = '.'; $extList = array(); $extList['gif'] = 'image/gif'; $extList['jpg'] = 'image/jpeg'; $extList['jpeg'

我使用的是这段很棒的随机数发生器代码:,但是图像不会保存在浏览器的缓存中,这意味着每当站点重新加载时,图像都会刷新

是否可以将图像缓存在以下代码中? 我使用此脚本的原因是,出于某种原因,css上的php解析无法在我的服务器上工作

<?php

$folder = '.';
$extList = array();
    $extList['gif'] = 'image/gif';
    $extList['jpg'] = 'image/jpeg';
    $extList['jpeg'] = 'image/jpeg';
    $extList['png'] = 'image/png';

$img = null;

if (substr($folder,-1) != '/') {
    $folder = $folder.'/';
}

if (isset($_GET['img'])) {
    $imageInfo = pathinfo($_GET['img']);
    if (
        isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
        file_exists( $folder.$imageInfo['basename'] )
    ) {
        $img = $folder.$imageInfo['basename'];
    }
} else {
    $fileList = array();
    $handle = opendir($folder);
    while ( false !== ( $file = readdir($handle) ) ) {
        $file_info = pathinfo($file);
        if (
            isset( $extList[ strtolower( $file_info['extension'] ) ] )
        ) {
            $fileList[] = $file;
        }
    }
    closedir($handle);

    if (count($fileList) > 0) {
        $imageNumber = time() % count($fileList);
        $img = $folder.$fileList[$imageNumber];
    }
}

if ($img!=null) {
    $imageInfo = pathinfo($img);
    $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
    header ($contentType);
    readfile($img);
} else {
    if ( function_exists('imagecreate') ) {
        header ("Content-type: image/png");
        $im = @imagecreate (100, 100)
            or die ("Cannot initialize new GD image stream");
        $background_color = imagecolorallocate ($im, 255, 255, 255);
        $text_color = imagecolorallocate ($im, 0,0,0);
        imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
        imagepng ($im);
        imagedestroy($im);
    }
}

?>

一种解决方案是使用cookie存储您发送给用户的图像,并始终发送该图像:

if(!isset($_COOKIE['imgCookie']))
{
    //runs if the user doesn't have the cookie
    //run randomizer code
    //setcookie('imgCookie',$imageNumber);
} else {
    //runs if the user already has the cookie
    $imagenumber=$_COOKIE['imgCookie'];
}
//run code for sending image to user

一种解决方案是使用cookie存储您发送给用户的图像,并始终发送该图像:

if(!isset($_COOKIE['imgCookie']))
{
    //runs if the user doesn't have the cookie
    //run randomizer code
    //setcookie('imgCookie',$imageNumber);
} else {
    //runs if the user already has the cookie
    $imagenumber=$_COOKIE['imgCookie'];
}
//run code for sending image to user

通过在标题中指定缓存持续时间,可以指示用户浏览器将页面缓存很长时间(最多一年,如下所示):

header('Cache-Control: max-age=31556926');

然而,对此有两个警告。首先,浏览器不一定遵循缓存指令,而且可能会选择下载图像的新副本。第二,这一行必须放在页面上任何内容之前的某个位置。

通过在标题中指定缓存持续时间,可以指示用户浏览器将页面缓存很长一段时间(最多一年,如下所示):

header('Cache-Control: max-age=31556926');

然而,对此有两个警告。首先,浏览器不一定遵循缓存指令,而且可能会选择下载图像的新副本。第二,这一行必须放在页面上任何内容之前的某个位置。

生成
E-tag
Cache Control
标题将有助于您这样做

<?php
  $folder   = '.';
  $extList  = array( "gif", "jpg", "jpeg", "png" );
  $image    = false;

  if ( substr( $folder, -1 ) != '/' ) {
    $folder = $folder.'/';
  }

  if ( isset( $_GET["img"] ) ) {
    $imageExtn  = strtolower( pathinfo( $_GET["img"], PATHINFO_EXTENSION ) );
    $imageName  = basename( $_GET["img"] );
    if ( in_array( $imageExtn, $extList ) && file_exists( $folder.$imageName ) ) {
      $image  = $folder.$imageName;
    }
  }
  else {
    $fileList = array();
    $handle   = opendir( $folder );
    while( false !== ( $file = readdir( $handle ) ) ) {
      $fileExtn = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
      if ( in_array( $fileExtn, $extList ) ) {
        $fileList[] = $file;
      }
    }
    closedir( $handle );

    if ( !empty( $fileList ) ) {
      $imageNumber  = time() % count( $fileList );
      $image  = $folder.$fileList[$imageNumber];
    }
  }

  if ( $image !== false ) {
    $contents = implode( "", file( $image ) );
    $md5  = md5( $contents );
    $mtime  = filemtime( $image );
    $etag = etag( $md5, $mtime );

    $r_mtime  = 0;
    $r_etag   = null;

    if ( isset( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) ) {
      $r_mtime  = strtotime( $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
    }
    if ( isset( $_SERVER["HTTP_IF_NONE_MATCH"] ) ) {
      $r_etag   = trim( $_SERVER["HTTP_IF_NONE_MATCH"] );
    }

    if ( $mtime == $r_mtime && $r_etag == $etag ) {
      header( "HTTP/1.0 304 Not Modified", true, 304 );
      header( "HTTP/1.1 304 Not Modified", true, 304 );
      header( "Content-length: 0" );
      exit;
    }

    header( "Content-type: image/".strtolower( pathinfo( $image, PATHINFO_EXTENSION ) ) );
    header( "Last-Modified: ".gmdate( "D, d M Y H:i:s", $mtime )." GMT" );
    header( "ETag: ".$etag );
    header( "Expires: ".gmdate( "D, d M Y H:i:s", time()+3600 )." GMT" );
    header( "Cache-Control: max-age=3600" );
    header( "Cache-Control: public" );

    echo $contents;
    exit();
  }
  else {
    if ( function_exists( "imagecreate" ) ) {
      header( "Content-type: image/png" );
      $im = @imagecreate( 100, 100 ) or die( "Cannot initialize new GD image stream" );
      $background_color = imagecolorallocate( $im, 255, 255, 255 );
      $text_color = imagecolorallocate( $im, 0, 0, 0 );
      imagestring( $im, 2, 5, 5,  "IMAGE ERROR", $text_color );
      imagepng( $im );
      imagedestroy( $im );
    }
  }

  function etag( $string_1 = null, $string_2 = null, $quote = true ) {
    $quote  = ( $quote ) ? '"' : '';
    $etag   = sprintf( $quote."%s-%s".$quote, $string_1, $string_2 );
    return $etag;
  }
?>

生成
电子标签
缓存控制
标题将有助于您这样做

<?php
  $folder   = '.';
  $extList  = array( "gif", "jpg", "jpeg", "png" );
  $image    = false;

  if ( substr( $folder, -1 ) != '/' ) {
    $folder = $folder.'/';
  }

  if ( isset( $_GET["img"] ) ) {
    $imageExtn  = strtolower( pathinfo( $_GET["img"], PATHINFO_EXTENSION ) );
    $imageName  = basename( $_GET["img"] );
    if ( in_array( $imageExtn, $extList ) && file_exists( $folder.$imageName ) ) {
      $image  = $folder.$imageName;
    }
  }
  else {
    $fileList = array();
    $handle   = opendir( $folder );
    while( false !== ( $file = readdir( $handle ) ) ) {
      $fileExtn = strtolower( pathinfo( $file, PATHINFO_EXTENSION ) );
      if ( in_array( $fileExtn, $extList ) ) {
        $fileList[] = $file;
      }
    }
    closedir( $handle );

    if ( !empty( $fileList ) ) {
      $imageNumber  = time() % count( $fileList );
      $image  = $folder.$fileList[$imageNumber];
    }
  }

  if ( $image !== false ) {
    $contents = implode( "", file( $image ) );
    $md5  = md5( $contents );
    $mtime  = filemtime( $image );
    $etag = etag( $md5, $mtime );

    $r_mtime  = 0;
    $r_etag   = null;

    if ( isset( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) ) {
      $r_mtime  = strtotime( $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
    }
    if ( isset( $_SERVER["HTTP_IF_NONE_MATCH"] ) ) {
      $r_etag   = trim( $_SERVER["HTTP_IF_NONE_MATCH"] );
    }

    if ( $mtime == $r_mtime && $r_etag == $etag ) {
      header( "HTTP/1.0 304 Not Modified", true, 304 );
      header( "HTTP/1.1 304 Not Modified", true, 304 );
      header( "Content-length: 0" );
      exit;
    }

    header( "Content-type: image/".strtolower( pathinfo( $image, PATHINFO_EXTENSION ) ) );
    header( "Last-Modified: ".gmdate( "D, d M Y H:i:s", $mtime )." GMT" );
    header( "ETag: ".$etag );
    header( "Expires: ".gmdate( "D, d M Y H:i:s", time()+3600 )." GMT" );
    header( "Cache-Control: max-age=3600" );
    header( "Cache-Control: public" );

    echo $contents;
    exit();
  }
  else {
    if ( function_exists( "imagecreate" ) ) {
      header( "Content-type: image/png" );
      $im = @imagecreate( 100, 100 ) or die( "Cannot initialize new GD image stream" );
      $background_color = imagecolorallocate( $im, 255, 255, 255 );
      $text_color = imagecolorallocate( $im, 0, 0, 0 );
      imagestring( $im, 2, 5, 5,  "IMAGE ERROR", $text_color );
      imagepng( $im );
      imagedestroy( $im );
    }
  }

  function etag( $string_1 = null, $string_2 = null, $quote = true ) {
    $quote  = ( $quote ) ? '"' : '';
    $etag   = sprintf( $quote."%s-%s".$quote, $string_1, $string_2 );
    return $etag;
  }
?>

有没有不使用cookies的方法?另外,虽然这段代码是2003年的,但它工作得很好,但我想知道是否有更简单的方法来实现同样的事情?我添加了另一个答案。有没有不使用cookies的方法来实现这一点?另外,虽然这段代码是2003年编写的,但效果很好,但我想知道是否有更简单的方法来实现同样的目标?我添加了另一个答案。