【问题标题】:PHP Curl mp3 download reseting meta dataPHP Curl mp3 下载重置元数据
【发布时间】:2013-08-29 15:37:28
【问题描述】:

我有一个下载 mp3 的网站,当我通过 php(curl) 下载它时,歌曲被下载,但专辑封面、艺术家姓名等歌曲的元数据丢失了。

在服务器上文件包含所有数据,但在下载时一切都丢失了。 这是我的代码:

if (!empty($path) && $path != null)
            {
                $ch = curl_init($path);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HEADER, true);
                $data = curl_exec($ch);
                curl_close($ch);
                if ($data === false)
                {
                    echo 'CURL Failed';
                    exit;
                }

                if (preg_match('/Content-Length: (\d+)/', $data, $matches))
                {
                    $contentLength = (int) $matches[1];
                }

                header("Pragma: public");
                header("Expires: 0");
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Cache-Control: private", false); // required for certain browsers
                header('Content-Type: audio/mpeg');
                header("Content-Disposition: attachment; filename=\"" . urlencode($song->title) . ".mp3\";");
                header('Content-Transfer-Encoding: binary');
                header('Content-Length: ' . $contentLength);
                ob_clean();
                flush();
                echo $data;
                exit;
            }

【问题讨论】:

    标签: php curl download mp3


    【解决方案1】:

    您正在强制 curl 将 hTTP 响应标头添加到您的 mp3 文件中,因此您将获得如下所示的内容:

    HTTP/1.1 ...
    Content-type: audio/mpeg
    Content-length: 12345
    
    ID3v2.......
    mp3 data here
    

    由于 ID3 数据不在您发送的数据的开头,因此音频播放器无法找到它,因为它看到的只是 HTTP 标头。

    如果您对这些标头所做的只是提取内容长度,那么为什么还要费心去做呢?您可以在 PHP 中使用strlen() 为您计算它。例如

    $mp3data = file_get_contents('url to mp3 file');
    $length = strlen($mp3data);
    
    header("Content-length: $length");
    echo $mp3data;
    

    【讨论】:

    • 可以重命名文件吗?
    • 太棒了,它成功了我刚刚添加了header("Content-Disposition: attachment; filename=\"" . urlencode($song->title) . ".mp3\";");,它成功了,非常感谢队友
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多