Search code examples
phphtml.htaccessplayback

playing mp3 from a folder which has .htaccess restriction for download


I have been trying to make a music streaming website.

I store all the mp3 in www.abc.com/audio folder .

This folder has .htaccess restriction so that none can download any file.

After so much of searching I am unable to find how to play mp3 from this folder using php from this folder.

The PHP code for the play file is filename: play.php

<?php
//print_r($_GET);
include_once('./functions.php');

$path=getPathFromHash($_GET['value']);   //get path from hash_value ex. www.abc.com/audio/1.mp3
echo $track = getFileNameFromHash($_GET['value']);  //get file name ex. 1.mp3

if (file_exists($track)) {
header("Content-Type: audio/mpeg");
header('Content-Length: ' . filesize($track));
header('Content-Disposition: inline; filename=' . $track);
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";
}


?>
<audio src="<?php echo $path?>" autoplay loop controls></audio>

my .htaccess file in audio folder is

<FilesMatch ".(ogg|mp3)$">
Order Allow,Deny
Deny from all
</FilesMatch>

But after all this, the song is not playing :( What changes should I make so that song starts to play?

Thank you in advance.


Solution

  • You have two problems that I can see:

    1)

    echo $track = getFileNameFromHash($_GET['value']);
    

    Remove the echo from this line. This will cause the file name to be output and will at least corrupt the file data, it will probably prevent the headers from being set correctly as well.

    2)

    You probably need to tell PHP that the files are in the audio/ directory. You say that getFileNameFromHash() returns ex. 1.mp3 - well PHP will look for 1.mp3 in the current working directory, which according to your comment above will be the webroot.

    Try changing the line mentioned above to

    $track = 'audio/' . getFileNameFromHash($_GET['value']);
    

    ...which will also mean you should change the Content-Disposition line to:

    header('Content-Disposition: inline; filename="' . basename($track) . '"');
    

    All of this assumes that $path contains a sensible value. It should be /play.php?value=<hash value expected by your functions>