I recently encountered a problem during a build of a site, where I was linking to MP3 files that the user could download.
The trouble with linking to media files, such as music, videos etc, is that the vast majority of browsers will try and stream the media by default, and this is something I had to try and overcome.
In the end, I found a simple piece of PHP script which enabled this process perfectly.
I have checked in IE6, IE7, Firefox and Safari, and all works well in each.
Here's how!
For this example, lets assume we are linking to an MP3 file, as I was during the build.
Originally my link looked like:
<a href="test.mp3">Download this MP3</a>
Firstly, instead of linking directly to the media file in question, link to a PHP page. We will come to the contents of this page in a second. So, your link instead will look like..
<a href="test.php">Download this MP3</a>
Now, lets get to the PHP page. Obviously you will need to firstly create the page, entitled test.php, or whatever you fancy.
It is important when placing this code in your php page, that this is the only code in the entire page, and that there are no spaces above or below the code.
So, within this page, paste the following:
<?php
header('Content-disposition: attachment; filename=test.mp3');
header('Content-type: audio/mp3');
readfile('test.mp3');
?>
You can see where you need to change the two references to the MP3 filename in the script. There is also another variable, audio/mp3. If you are linking to a different audio filetype, for example a .wma file, change this to audio/wma. Similarly this will need changing if linking to a video file.
And there you have it. Upload all the files to the server, and you are done.
Labels: Web Development