2017-04-02 100 views
0

下圖顯示此代碼:PHP:強制下載是下載一個空文件

/home/my_site/www/wp-content/uploads/2017/03/2017-03-17-my_file.mp3 

據我所知,這條道路是正確的。但是,當我註釋掉echo並下載文件時,它是一個空文件。爲什麼?

代碼:

if (isset($_GET['file'])) { 
    clearstatcache(); 
    $file_path = str_replace('http://www.example.com/', '', $_GET['file']); 
    $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path . '.mp3'; 
    echo $file_path; 

    if(file_exists($file_path)) { 
     $file_name = basename($file_path); 
     $file_size = filesize($file_path); 
     header("Cache-Control: private"); 
     header("Content-Type: application/stream"); 
     header("Content-Length: ".$file_size); 
     header("Content-Disposition: attachment; filename=".$file_name); 
     exit(); 
    } 
    else { 
     die('The provided file path is not valid.'); 
    } 
} 

編輯:這是我KIKO軟件的建議後。仍下載空文件。

<?php 
if (isset($_GET['file'])) { 
    $file_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $_GET['file'] . '.mp3'; 
    //echo $file_path; 
    //$file_path = $_SERVER['SCRIPT_FILENAME']; 
    if (file_exists($file_path)) { 
    $file_name = basename($file_path); 
    $file_size = filesize($file_path); 
    header('Content-type: application/octet-stream'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: '.$file_size); 
    header('Content-Disposition: attachment; filename='.$file_name); 
    //readfile($file_path); 
    exit(); 
    } 
    else { 
     die('The provided file path is not valid.'); 
    } 
} 
?> 

回答

2

簡單的例子來下載文件:

$content = 'This is the content.'; 
$size = strlen($content); 
$name = 'test.txt'; 
header('Content-type: application/octet-stream'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: '.$size); 
header('Content-Disposition: attachment; filename='.$name); 
echo $content; 

確保該工程第一。如果沒有,那麼標題可能會有問題。打開錯誤報告,並看到:How to fix "Headers already sent" error in PHP

然後建立在那。首先下載腳本本身:

$file_path = $_SERVER['SCRIPT_FILENAME']; 
if (file_exists($file_path)) { 
    $file_name = basename($file_path); 
    $file_size = filesize($file_path); 
    header('Content-type: application/octet-stream'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: '.$file_size); 
    header('Content-Disposition: attachment; filename='.$file_name); 
    readfile($file_path); 
    exit(); 
} 
else { 
    die('The provided file path is not valid.'); 
}  

並且只有在嘗試下載別的東西之後。

通過逐步處理問題,可以更輕鬆地查看問題出在哪裏。

+0

如果我這樣做,Firefox崩潰並且根本沒有文件下載......在Chrome中,我看到文件的(亂碼)內容,也沒有文件下載。 – drake035

+0

我不得不承認,我沒有測試你的代碼。 'readfile()'是正確的,所以這不會導致你有問題。我稍微更改了標題,也許這會有所幫助?他們不是標準的。當您使用url時,請閱讀'readfile()'手冊。 **如果fopen包裝已啓用,則可以使用此URL作爲文件名。** –

+0

另請參閱:https://stackoverflow.com/help/mcve如果您希望人們爲您提供工作代碼。 –