使用 php 生成 php 电子标签

apa*_*pak 2 php xml apache etag cache-control

此 PHP 代码为 xml 文件生成 eTag。问题是 eTag 仅当文件本身更新/修改时才会更新。当动态结果更新时,我也需要更新 etag。知道如何做到这一点吗?

//get the last-modified-date of this very file
$lastModified=filemtime(__FILE__);

//get a unique hash of this file (etag)
$etagFile = md5_file(__FILE__);

//get the HTTP_IF_MODIFIED_SINCE header if set
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);

//get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash)
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);

//set last-modified header
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");

//set etag-header
header("Etag: $etagFile");

//make sure caching is turned on    
//check if page has changed. If not, send 304 and exit
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile)
{
       header("HTTP/1.1 304 Not Modified");
       exit;
}
Run Code Online (Sandbox Code Playgroud)

bys*_*n22 5

你可以做这样的事情。
获取动态内容而不是文件的唯一哈希值并将其设置为eTag.

<?php
  $last_modified  = filemtime( __FILE__ );

  $modified_since = ( isset( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) ? strtotime( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) : false );
  $etagHeader     = ( isset( $_SERVER["HTTP_IF_NONE_MATCH"] ) ? trim( $_SERVER["HTTP_IF_NONE_MATCH"] ) : false );

  // This is the actual output from this file (in your case the xml data)
  $content  = 'your xml data from db or file';
  // generate the etag from your output
  $etag     = sprintf( '"%s-%s"', $last_modified, md5( $content ) );

  //set last-modified header
  header( "Last-Modified: ".gmdate( "D, d M Y H:i:s", $last_modified )." GMT" );
  //set etag-header
  header( "Etag: ".$etag );

  // if last modified date is same as "HTTP_IF_MODIFIED_SINCE", send 304 then exit
  if ( (int)$modified_since === (int)$last_modified && $etag === $etagHeader ) {
    header( "HTTP/1.1 304 Not Modified" );
    exit;
  }

  // new content or file modified, so output ypur content
  echo $content;
  exit;
?>
Run Code Online (Sandbox Code Playgroud)