2009-10-04 58 views
10

我工作的一種方法,通過PHP和後一些幫助的形式如此大量的服務了MP3文件設置Apache服務PHP,我得到了它的工作here當請求MP3文件

然而,例如沒有出現,當我在音頻標籤使用它作爲源這樣

<html> 
    <head> 
     <title>Audio Tag Experiment</title> 
    </head> 
    <body> 

    <audio id='audio-element' src="music/mp3.php" autoplay controls> 
    Your browser does not support the audio element. 
    </audio> 

    </body> 
</html> 

工作,這裏的PHP

<?php 

$track = "lilly.mp3"; 

if(file_exists($track)) 
{ 
header("Content-Transfer-Encoding: binary"); 
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3"); 
header('Content-length: ' . filesize($track)); 
header('Content-Disposition: filename="lilly.mp3"'); 
header('X-Pad: avoid browser bug'); 
Header('Cache-Control: no-cache'); 

readfile($track); 
}else{ 
    echo "no file"; 
} 

所以我想(這可能是AR你告訴我),我可能會設置Apache來在有人請求.MP3時爲PHP文件提供服務。

所以我三個問題

  1. 將這項工作
  2. 好主意/壞主意?
  3. 我需要做什麼?將「AddType應用程序/ x-httpd-php .mp3」int他httpd conf做到這一點?

回答

17

有在你的代碼中的一些錯誤:

  • 資源只能有一個單一的Content-Type值。所以你必須決定你想使用的媒體類型。我建議audio/mpeg
  • 您忘記指定配置Content-Disposition。如果您只想提供文件名並且不想更改處置,請使用默認值inline

其餘的看起來不錯。但是如果找不到文件,我也會發送404狀態碼。

$track = "lilly.mp3"; 

if (file_exists($track)) { 
    header("Content-Type: audio/mpeg"); 
    header('Content-Length: ' . filesize($track)); 
    header('Content-Disposition: inline; filename="lilly.mp3"'); 
    header('X-Pad: avoid browser bug'); 
    header('Cache-Control: no-cache'); 
    readfile($track); 
    exit; 
} else { 
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404); 
    echo "no file"; 
} 
+0

天才!內聯做了訣竅,我已經整理了Content-Type,現在我正在發送一個404。 – gargantuan 2009-10-04 16:39:38

4

你可以簡單地做到這一點,以便你有一個mod_rewrite規則來通過你的mp3.php文件運行每個音樂/ *。mp3的請求。

例如,像這樣

RewriteEngine on 
RewriteRule ^/music/(.*\.mp3) /music/mp3.php?file=$1 [L] 

mp3.php然後可以拿起從$ _ GET請求的文件[「文件」],但如果你用這種方法,我建議你去合法性檢查文件名,以確保它僅引用所需目錄中的文件。

//ensure filename just uses alphanumerics and underscore 
if (preg_match('/^[a-z0-9_]+\.mp3$/i', $_GET['file'])) 
{ 
    //check file exists and serve it 

    $track=$_SERVER['DOCUMENT_ROOT'].'/music/'.$_GET['file']; 
    if(file_exists($track)) 
    { 
     header("Content-Type: audio/mpeg"); 
     header('Content-length: ' . filesize($track)); 
     //insert any other required headers... 

     //send data 
     readfile($track); 
    } 
    else 
    { 
     //filename OK, but just not here 
     header("HTTP/1.0 404 Not Found"); 
    } 

} 
else 
{ 
    //bad request 
    header("HTTP/1.0 400 Forbidden"); 
} 
+0

這工作過,但對方的回答是......更純潔,我猜。雖然這確實提醒我使用.htaccess來防止人們直接訪問文件。乾杯。 – gargantuan 2009-10-04 16:41:09

+0

該解決方案可讓您擁有.mp3網址,但可讓您使用某些PHP攔截這些請求。這不是你想要的,但我開始了,所以我完成了! – 2009-10-04 16:45:00

+0

很好的努力。某個地方會發現有用的。 – gargantuan 2009-10-04 17:17:08

0

這一個工作對我來說(在.htaccess):

<FilesMatch "mp3$"> 
    SetHandler application/x-httpd-php5 
</FilesMatch>