2016-07-29 115 views
1

爲了安全起見,我有一個名爲Pdf的文件夾中的PDF文件,位於public_html之外。訪問文件public_html使用codeigniter 3.X

我試圖從位於應用程序文件夾內的我的控制器訪問此文件。 我試過使用幾條路徑..

一個是:../../../../Pdf/{$name_hash}.pdf。 另一個是:/home/xx/Pdf/{$name_hash}.pdf

我想包括文件,並把它作爲一個js.openwindow以及readfile($filepath)都無濟於事!

這些文件是存在的,名稱也由哈希函數正確生成,所以我確定它是設置問題的路徑。

是否有一些CI規則,我沒有遵循設置路徑?或者是否有任何其他解決方案,請幫助!

回答

1

問題是,您無法在瀏覽器url中訪問public_html(或虛擬主機設置域的目錄)後面的文件。您必須獲取文件的內容並通過緩衝區將其發送到輸出。您可以使用readfile($file)對於PHP內置功能:

public function pdf() 
{ 
    // you would use it in your own method where $name_hash has generated value 
    $file = "/home/xx/Pdf/{$name_hash}.pdf"; 

    if (file_exists($file)) { 
     header('Content-Description: File Transfer'); 
     header('Content-Type: application/pdf'); 
     // change inline to attachment if you want to download it instead 
     header('Content-Disposition: inline; filename="'.basename($file).'"'); 
     header('Expires: 0'); 
     header('Cache-Control: must-revalidate'); 
     header('Pragma: public'); 
     header('Content-Length: ' . filesize($file)); 
     readfile($file); 
    } 
    else "Can not read the file"; 
} 

PHP docsexample