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

前端 未结 4 1925
广开言路
广开言路 2020-12-09 12:37

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

相关标签:
4条回答
  • 2020-12-09 12:58

    Use the header x-sendfile instead of readfile for better performanse.

    http://john.guen.in/past/2007/4/17/send_files_faster_with_xsendfile/

    0 讨论(0)
  • 2020-12-09 13:04

    You could simply make it so that you have a mod_rewrite rule to run every request for music/*.mp3 through your mp3.php file.

    For example, something like this

    RewriteEngine on
    RewriteRule ^/music/(.*\.mp3)    /music/mp3.php?file=$1 [L]
    

    mp3.php can then pick up the requested file from $_GET['file'], but if you go with this approach I recommend you sanity check the filename, to ensure it only references a file in the desired directory.

    //ensure filename just uses alphanumerics and underscore
    if (preg_match('/^[a-z0-9_]+\.mp3$/i', $_GET['file']))
    {
        //check file exists and serve it
    
        $track=$_SERVER['DOCUMENT_ROOT'].'/music/'.$_GET['file'];
        if(file_exists($track))
        {
            header("Content-Type: audio/mpeg");
            header('Content-length: ' . filesize($track));
            //insert any other required headers...
    
            //send data
            readfile($track);
        }
        else
        {
            //filename OK, but just not here
            header("HTTP/1.0 404 Not Found");
        }
    
    }
    else
    {
        //bad request
        header("HTTP/1.0 400 Forbidden");
    }
    
    0 讨论(0)
  • 2020-12-09 13:06

    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";
    }
    
    0 讨论(0)
  • 2020-12-09 13:13

    This one works for me (in .htaccess):

    <FilesMatch "mp3$">
        SetHandler application/x-httpd-php5
    </FilesMatch>
    
    0 讨论(0)
提交回复
热议问题