Welcome to the Geeks & God Static Archive. Read more »

force download of mp3 in PHP

Joined: 06/10/2009


I have a listen and a download link for each sermon.

I am using PHP and using Komodo edit to do my editing.

I have been able to get the website visitor to listen to the MP3, and that works fine. I don't know how to make the download link work though.

Any help would be much appreciated.



G&G Podcast Host
Matt Farina's picture
Joined: 06/01/2006

I take it you are linking to a file. Is that right?

What you want is for the headers sent with the file to say the Content Disposition is an attachment. That will tell the browser to download it.

If you're using apache you can do something like:

<FilesMatch "\.(?i:mp3)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment

This will tell IE that it's an application file and other browsers that it's an attachment to be downloaded. In the FilesMatch part is a regular expression to look for mp3 files with upper or lowercase letters.

This would go in the directory of your files or one above it and in a .htaccess file. Or, it can go in your apache config if you have access to that.

Matt Farina
Geeks and God Former Co-Host

Joined: 08/17/2009
PHP Headers

In case you don't have access/authority to use .htaccess to create the needed headers, you could create a simple "view" page in php that creates the headers and outputs the mp3.

header("Content-Description: Harcourt Industries - {$fileName}");
header("Content-length: {$fileSize}");
header("Content-Disposition: attatchment; filename={$fileName}");
echo $mp3

The use will actually never see the view page since it contains no content - it serves as a download point (it can also be used to do data tracking - updates a table keeping track of what is downloaded and how much).