2013-07-27 80 views
1

有一個代碼來下載的zip文件:我如何從外部根目錄訪問文件在PHP

$dl_path = './'; 
$filename = 'favi.zip'; 
$file = $dl_path.$filename; 
if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/zips');  
    header("Pragma: public");  
    header("Expires: 0");  
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); 
    header("Content-Type:application/force-download");  
    header("Content-Type:application/download"); 
    header("Content-Disposition:attachment;filename=$filename ");  
    header("Content-Transfer-Encoding:binary "); 
    header('Content-Length: ' . filesize($file)); 
    ob_clean(); 
    flush(); 
    readfile($file); 
    exit; 
} 

有根目錄/public_html,該腳本在根目錄下執行。

/目錄中有zip文件。

我正在嘗試使用$dl_path作爲/,但它不起作用。

請幫忙。

+1

1.正確格式化您的代碼; 2.使用../作爲路徑移動到public_html –

+1

3.檢查權限 –

回答

8
$dl_path = __DIR__.'/..'; // parent folder of this script 
$filename = 'favi.zip'; 
$file = $dl_path . DIRECTORY_SEPARATOR . $filename; 

// Does the file exist? 
if(!is_file($file)){ 
    header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found"); 
    header("Status: 404 Not Found"); 
    echo 'File not found!'; 
    die; 
} 

// Is it readable? 
if(!is_readable($file)){ 
    header("{$_SERVER['SERVER_PROTOCOL']} 403 Forbidden"); 
    header("Status: 403 Forbidden"); 
    echo 'File not accessible!'; 
    die; 
} 

// We are good to go! 
header('Content-Description: File Transfer'); 
header('Content-Type: application/zip'); 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Type: application/download"); 
header("Content-Disposition: attachment;filename={$filename}"); 
header("Content-Transfer-Encoding: binary "); 
header('Content-Length: ' . filesize($file)); 
while(ob_get_level()) ob_end_clean(); 
flush(); 
readfile($file); 
die; 

^嘗試此代碼。看看它是否有效。如果沒有:

  • 如果404的表示該文件未找到。
  • 如果它403的這意味着你不能訪問它(權限問題)
+0

是的,它的工作,感謝你。一個小東西,下載的文件保存爲「favi.zip」而不是favi.zip。如何改變這一點。 – RJ501

+0

修復了'header(「Content-Disposition:attachment; filename = {$ filename}」);'現在正常工作。 – CodeAngry

0

首先通過回顯dirname(__FILE__)來檢查腳本是否在正確的目錄下運行。

如果public_html下運行,那麼你可以改變這樣的代碼:

$dl = dirname(__FILE__). '/../'; 

但安全問題的注意!

  1. 檢查您已經閱讀該文件目錄/寫權限
  2. 檢查open_basedir限制在php.ini(見How can I relax PHP's open_basedir restriction?

希望這有助於

相關問題