2011-10-27 56 views
-1

設置標題是我的下載網關的代碼,某些部分錯誤在PHP

if (!isset($_GET['f']) || empty($_GET['f'])) {die("<h1>URL Malfunction</h1><br/><p><i>Please Try Later</i>");} 
if (strpos($_GET['f'], "\0") !== FALSE){ die("<h1>URL Malfunction</h1><br/><p><i>Please Try Later</i>");} 
          #Check URL, find resource Path 

$fileName = basename($_GET['f']); 
$file_path=(string)makeDownloadFilePath($fileName,"dir"); 

if(!is_file($file_path)){die("<h1>404 Not found</h1><br/><p><i>The resource you requested is not available</i>");} 

$fileSize = filesize($file_path); 



header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: public");     #Build Response# 
header("Content-Description: File Transfer"); 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=\"$fileName\""); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: " . $fileSize); 


$file = @fopen($file_path,"rb"); 
if ($file) { 
    while(!feof($file)) {     #File Transfer# 
    print(fread($file, 1024*8)); 
    flush(); 
    if (connection_status()!=0) { 
    @fclose($file); 
    die(); 
     } 
    } 
@fclose($file); 

//The File is Downloaded . Closing Connections 

我使用GET方法來接收文件名。文件名及其路徑將從網關生成。現在的問題是,當我點擊下載頁面,而不是顯示下載對話框時,瀏覽器只是將文件內容呈現爲屏幕上的文本。例如,我正在下載foo.mp3。二進制內容在屏幕上顯示爲怪異文本。它迴應瞭如下警告:我們不能更改標題。標題已發送到...

任何人都可以告訴,我犯了什麼錯誤?

感謝

+0

這不是錯誤消息。只需將* real *錯誤消息複製並粘貼到Google,即可找到。 – mario

+0

[Headers already sent]可能重複(http://stackoverflow.com/questions/2938777/headers-already-sent) – mario

+0

錯誤信息?我只能在瀏覽器中看到該警告。那麼它開始將文件呈現爲文本 – Kris

回答

1

我們無法改變的標題。頭已經發送到..

這個錯誤是當你打印任何東西之前php你的頭部命令。

+0

我已經使用die()on條件。但是這隻會發生在真實的情況下。 – Kris

+0

你死了沒問題,但是你在其他地方打印某些東西,這是肯定的。你可能包括這個文件嗎? – peko

+0

你的意思是include()?.我在這個文件中有4個包含指令。 – Kris

0

使用ReadFile的,而不是作爲的fopen遵循和使用ob_clean(),使用ob_flush():

header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="'.$Name.'"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: '.filesize($musicPath)); 
    ob_clean(); 
    flush(); 
    readfile($musicPath); 
    ob_flush(); 
+0

不變。它的輸出相同。 – Kris

0

您使用的輸出緩衝?

嘗試添加ob_start();然後您發送標題信息,這可能會解決您的問題。

你可以找到更多關於它的信息here

1

長久以來這種錯誤最常見的原因是您在文件(或其中一個包含的文件)中打開<?php標記之前有一些主要的空白區域。

<應該是文件中的第一個字符,之前的東西,它直接寫入輸出緩衝區,並可能會導致頭被髮送。當以這種方式強制文件下載時,它也會導致文件損壞。

+0

我沒有任何空格之前'<' – Kris

+0

你有沒有檢查您的包含文件(S)以及? – DaveRandom

0

謝謝大家的幫助。問題是我正在使用一個

error_reporting(E_ALL); 
ini_set('display_errors', true); 
flush(); 

調試我的包括之一。

我剛剛刪除它。現在它的工作。