views:

16

answers:

2

Hi folks, I have a page with mp3s that are playable from a player, and there are also links to download the songs. When the user clicks on the download link, it needs to open the download dialog instead of opening a media player, so it was recommended to me to use this header script:

includes/auto-download.php:

<?php
$path = $_GET['path'];
header('Content-Disposition: attachment; filename=' . basename($path));
readfile($path);
?>

And then on my main page, the link looks like this:

<a href="includes/auto_download.php?path=Media/Audio/Date/song.mp3">Song Name</a>

I seem to be doing something wrong with my paths, as when I click the link, the download box opens, and I can download a file with the correct name, but it doesn't contain any information.

To elaborate on my file structure, I've got this:

/Patrons (where my main index.php page is with my link

/Patrons/includes (where my auto-download.php script is)

/Patrons/Media/Audio/Date/ (this is where all the songs are)

Any help would be greatly appreciated!

+1  A: 

Either change HTML code to this:

 <a href="includes/auto_download.php?path=../Media/Audio/Date/song.mp3">Song Name</a>

OR change PHP code to this:

 readfile('../'.$path);
shamittomar
I came back to delete this, because I just figured it out too-but you answered in time! :-D Thanks for taking the time!
Joel
A: 

$path needs to be the relative path to the file from the web root. with no leading slash. If the files are outside the web root you should use a fullpath (/home/webuser/song_files/song.mp3).

For example $path = 'song_files/'. $_GET['name_of_the_file'];

You should also check if the file does not exist and exit with an error. Here is an example I made in codeigniter.

function _begin_download($document_data) {
    basepath = 'uploads/';
    $filepath = basepath . $document_data->filename;
    if (file_exists($filepath)) {
        header("Content-type: " . $document_data->mimetype);
        header("Content-length: " . filesize($filepath));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-disposition: attachment; filename="' . $document_data->filename . '"');
        readfile($filepath);
        exit();
    } else {
        exit('File not found.');
    }
}
Keyo