【问题标题】:PHP Download MP3 files from directory on serverPHP 从服务器上的目录下载 MP3 文件
【发布时间】:2017-04-14 18:47:34
【问题描述】:

我正在尝试将 MP3 文件下载到位于服务器上名为“songs”的目录中的用户计算机。我已经能够运行通过浏览器下载这些文件的脚本。但是,这些文件严格下载为扩展名为 .mp3 的文本。我希望这些文件在从服务器下载后成为可播放的 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年他爱飞.mp3'>01 1983年他爱飞.mp3

【问题讨论】:

  • 什么是正确的位置 mp3 文件? print $file; 在调用 readfile($file); 之前。它说什么?
  • 我尝试在调用 readfile 之前打印 $file。下载返回相同的结果。似乎很奇怪。 @user4035
  • MP3 文件位于服务器上名为“songs”的目录中,我已将其作为目标。 @user4035
  • 使用$target变量
  • 所有这些代码是否都驻留在同一个文件/脚本中?

标签: php download mp3


【解决方案1】:

首先,header()应该在任何输出之前发送,包括echoprint_r、任何html、开始标记之前的空格(例如&lt;?php)。参考 给the manual

其次,如果你想用文件的内容响应浏览器,你的脚本不应该输出任何其他内容。除内容外的任何输出都将被视为内容的一部分。除非您将它作为多部分发送并且您的客户能够处理它。

举个例子

<?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
header("Content-Length: ".filesize($file));

readfile($file);

【讨论】:

  • 说真的,您的link 与@sumitkumarpradhan 的问题有什么关系?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2018-12-13
  • 2017-10-18
  • 1970-01-01
  • 2018-01-02
相关资源
最近更新 更多