在PHP中测试304响应代码实现

问题描述 投票:0回答:1

我有一个API,我一直在尝试向其中添加缓存控制标头。

API已经使用PhpFastCache进行服务器端缓存,但是我想添加浏览器控件缓存的附加层。我遇到了this智能php缓存控制页面,并对其进行了一些修改。

使用PhpFastCache,我检查服务器端缓存是否存在,如果不存在,则查询数据库并正常输出200响应代码。如果缓存确实存在,那么我将执行以下操作:

//get the last-modified-date of this very file
$lastModified=filemtime(__FILE__);
//get a unique hash of this file (etag)
$etagFile = md5( $CachedString->get() );
//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
header('Cache-Control: public');

//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;
}else{
    //Cache Match - Output Cache Result
    header('Content-Type: application/json');
    echo $CachedString->get();        
}   

我正在使用此行来获取作为md5缓存的响应:

$etagFile = md5( $CachedString->get() );

然后检查此md5内容是否已更改:

if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile)
{
   header("HTTP/1.1 304 Not Modified");
   exit;
}else{
    //Cache Match - Output Cache Result
    header('Content-Type: application/json');
    echo $CachedString->get();        
} 

但是我似乎永远无法获得304响应标头。它总是一个200码的响应头。

curl -I -L  https://db.ygoprodeck.com/api/v7/cardinfo.php?name=Tornado%20Dragon

响应始终为:

HTTP/1.1 200 OK
Date: Tue, 17 Mar 2020 13:37:31 GMT
Content-Type: application/json
Connection: keep-alive
Set-Cookie: __cfduid=daaab295934a2a8ef966c2c70fe0955b91584452250; expires=Thu, 16-Apr-20 13:37:30 GMT; path=/; domain=.ygoprodeck.com; HttpOnly; SameSite=Lax
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
Cache-Control: public
Last-Modified: Tue, 17 Mar 2020 13:15:53 GMT
Etag: 399b9ba2d69ab115f46faa44be04d0ca
Vary: User-Agent
CF-Cache-Status: DYNAMIC
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 57571be8a986a72f-DUB
php caching browser-cache phpfastcache
1个回答
1
投票

您的请求正在通过拥有自己缓存层的Cloudflare进行代理。如果您将此测试直接测试到原点/灰色记录模糊,您是否得到304?

[您说过您正在处理浏览器缓存,浏览器将根据您发送的max-age设置进行缓存,但看不到响应中设置了一个。

© www.soinside.com 2019 - 2024. All rights reserved.