簡體   English   中英

在 PHP 中測試 304 響應代碼實現

[英]Testing a 304 response code implementation in PHP

我有一個 API,我一直在嘗試向它添加緩存控制標頭。

API 已經將PhpFastCache用於服務器端緩存,但我想添加一個額外的瀏覽器控件緩存層。 偶然發現了這個智能的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

您的請求是通過 Cloudflare 代理的,它有自己的緩存層。 如果您直接測試原始/帶有灰色雲記錄的記錄,您會得到 304 嗎?

您說您正在處理瀏覽器緩存,瀏覽器將根據您發送的 max-age 設置進行緩存,但在響應中沒有看到設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM