2014-12-31 86 views
0

如何顯示文檔根目錄外的圖像。準確地說如何在根目錄以外的codeigniter中顯示圖像

/ <-- root directory 
/public_html/ <-- document root 
/application/upload/img <-- here is the source of image 

我在codeigniter和它的作品,但有一個很大的延遲,如果我嘗試加載多次。我這是在codeigniter中的幫助函數來幫助我,並加快我的時間來加載文件。

我展示的代碼是什麼,我有寫:

這是控制器:

public function img($img_name){ 
    $t = $this->getupload->Get($img_name); // here is taked from DB using MODEL 
    header("Pragma: public"); 
    header("Content-type: {$t[0]['file_type']}"); // Take the file type (eg: images/jpg) from DB 
    header('Content-Transfer-Encoding: binary'); 
    flush(); 
    readfile($t[0]['full_path']); // here take the imgfile from DB 
} 
+5

爲什麼不把文件移動到公共目錄?目前,您的應用程序不得不將圖像複製到內存中,然後吐出。只要讓你的http服務器完成它的內置工作,它會更快。 – castis

+1

@castis我能想到的唯一原因就是如果圖像是用戶提交的(它似乎是因爲文件夾名稱是「.../upload/...」),因爲它通常是最佳實踐不允許用戶上傳東西到webroot中。 –

+0

@Jonathan Kuhn你是對的,我想做一個安全的上傳,如果有任何「黑客」試圖破壞腳本,無法訪問文件上傳。 – Cosmin

回答

1

如果你希望你的服務器的工作,而不是代碼。

您應該配置您的apache或nginx以從該路徑獲取數據。

在apache的htaccess你可以嘗試:

RewriteRule ^uploads/(.*)$ /var/www/application/upload/img/$1 [R=301,NC,L] 

我不知道它會工作,但這是一個想法。

在nginx的

你可以檢查這樣的事情:

location /uploads/* { 
    try_files /var/www/application/upload/img/$query_string; 
} 

再次我不知道它會工作,因爲我不是一個服務器主, 但如果這是你想完成什麼我會建議檢查一下。

+0

如果我這樣做,我可以直接訪問這些文件...如果你知道任何爲什麼只是從localhost(php),而不是直接接受accesibles。 – Cosmin

+1

所以如果是爲了安全,所以你必須通過PHP寫你的帖子,你可以使用緩存來減少使用 –