2017-04-14 108 views
0

我试图将MP3文件下载到位于服务器上名为“歌曲”目录中的用户计算机上。我已经能够运行一个脚本,通过浏览器下载这些文件。但是,这些文件严格按照带.mp3扩展名的文本进行下载。我希望这些文件是从服务器下载的可播放mp3文件。PHP从服务器上的目录下载MP3文件

这是我的PHP脚本。

<?php 

$link = mysqli_connect("...","...","....","...") or die("Error ".mysqli_error($link)); 

if(mysqli_connect_errno()) 
{echo nl2br("Failed to connect to MySQL:". mysqli_connect_error() . "\n");} 
else 
{echo nl2br("Established Database Connection \n");} 

//当前的脚本下载所有歌曲列表上的服务器

$target = "songs/"; 


if ($handle = opendir($target)) { 
    while (false !== ($entry = readdir($handle))) { 
     if ($entry != "." && $entry != "..") { 
      echo $entry."'>".$entry."</a>\n"; 
     } 
    } 
    closedir($handle); 
} 


$file = basename($_GET['file']); 
$file = 'Songs_From_Server'.$file; 

if(!$file){ // file does not exist 
    die('file not found'); 
} else { 


    header("Cache-Control: private"); 
    header("Content-type: audio/mpeg3"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Disposition: attachment; filename=".basename($file)); 


    readfile($file); 

}发现

?>

下面是结果我得到的一个例子一个txt文件。

建立的数据库连接
01在1983年他爱Fly.mp3' > 01。1983年他爱Fly.mp3

+0

什么是正确的位置MP3文件? 'print $ file;'在调用'readfile($ file);'之前''。它说什么? – user4035

+0

我已经尝试在调用readfile之前打印$ file。下载返回相同的结果。看起来很奇怪。 @ user4035 – gsanchez

+0

MP3文件驻留在目标服务器上名为“songs”的目录中。 @ user4035 – gsanchez

回答

1

首先,header()应任何输出,其中包括echoprint_r,任何之前发送html,开始标记之前的空格(例如,<?php)。其次,如果你想用浏览器的文件内容进行响应,你的脚本不应该输出任何其他内容。除内容之外的任何输出都将被视为内容的一部分。除非您将它作为多部分发送并且您的客户端能够处理它。

所以,一个例子

<?php 

$fileName = $_GET['file']; 
$path = '/directory/contains/mp3/'; 
$file = $path.$fileName 

if (!file_exists($file)) { 
    http_response_code(404); 
    die(); 
} 

header("Cache-Control: private"); 
header("Content-type: audio/mpeg3"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Disposition: attachment; filename=".$fileName); 
//So the browser can display the download progress correctly 
header("Content-Length: ".filesize($file); 

readfile($file);