Search code examples
phpaudiohtmlmp3

Setting up apache to serve PHP when an MP3 file is requested


I'm working on a way to serve up MP3 files through PHP and after some help form the SO massive, I got it working here

However, that example doesn't appear to work when I use it as the source in an audio tag like this

<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>

and here's the 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";
}

So I'm thinking (and this may be a really bad idea, you tell me) that I might be able to set up Apache to serve a PHP file when someone requests an .MP3.

So I've three questions

  1. Will this work
  2. Good Idea / Bad Idea?
  3. What would I need to do? Would putting "AddType application/x-httpd-php .mp3" int he httpd conf do it?

Solution

  • There are some errors in your code:

    • A resource can only have one single Content-Type value. So you have to decide what media type you want to use. I suggest audio/mpeg.
    • You forgot to specify the disposition in Content-Disposition. If you just want give a filename and don’t want to change the disposition, use the default value inline.

    The rest looks fine. But I would also send the 404 status code if the file cannot be found.

    $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";
    }