PHP Curl mp3下载重置元数据


PHP Curl mp3 download reseting meta data

我有一个网站,可以下载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;
            }

您正在强制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;