2013-10-07 19 views
0

我已經實現了對服務器或其他受保護圖像的媒體視圖。控制器處理請求並檢查權限,並相應地用$this->response->file來服務器文件。在CakePhp中緩存使用response-> file()發送的圖像

但是,我還沒有設法獲取圖像緩存,迫使瀏覽器總是重新下載(我知道這是從Firebug的網絡面板)。這些文件不太可能發生變化,因此緩存會大大加快速度。

我玩過$this->response->modified()cache(),但無濟於事。

我該如何在控制器操作中實現一個檢查來服務器文件還是不修改狀態碼?還是我在這裏?

任何幫助表示讚賞! :)

public function view($id) 
{ 
    $this->loadModel('Image'); 
    $res = $this->Image->hasAccess($id, $this->Auth->user('subject_id')); 

    if($res['access'] || $this->isAdmin()){ 
     $modified = gmdate("D, j M Y G:i:s ", filemtime (APP . "Content/Images/" . $res['file'])); 
     $this->response->modified($modified); 
     $this->response->expires(time() + 60 * 60 * 24 * 31); 

     $this->response->file(APP . "Content/Images/" . $res['file']); 

    }else if($res['access'] === false){ 
     $this->response->statusCode(403); 
    }else if($res['access'] === null){ 
     $this->response->statusCode(404); 
    } 

    return $this->response; 
} 

回答

2

我認爲,更好的辦法是如果你使用nginx的添加頁眉在你的虛擬主機文件,例如:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { 
    expires 1y; 
    log_not_found off; 
} 

這種解決方案,因爲下一次的nginx不使用PHP來發送文件到它的更好用戶。

+1

忠言但如果反應出來的PHP,也不會適用,因爲Web服務器不發送響應的事情。對於靜態文件,大多數網絡服務器的等效規則可以在[html5樣板文件](https://github.com/h5bp)項目中找到 - 以及其他最佳做法。 – AD7six

+1

更正[在閱讀我可能自己寫的信息之後](https://github.com/h5bp/server-configs-nginx/blob/master/conf/expires.conf#L4-L5)我以前的評論是錯誤的:) 。鑑於+1 – AD7six