| ||||||
|
How users can download a MP3 file from your website with the help of PHP
Most browsers plain and simple have not got a clue about how to deal with mp3 files. If you link to a PDF or word document they will play along, open a new window and display the document. Not so with MP3s. On your standard Internet Explorer (yes, even on version 8), it will just try to open the MP3 as a page, and will then give you an error message as if it was your fault for trying to give it an impossible task. While other browsers do fair slightly better (Netscape at least opens the file with the users default music player), if you are a band (starting out), and actually want to distribute your music to your listeners as MP3s, you will have to force the download from a server side position. The way to do this in PHP is of course with header commands. Note that these have to be placed at the beginning, literally right at the beginning, not halfway through the script, or at the top of an include page, but indeed right at the beginning of your loaded page! <?php if($_GET['realname'] != NULL) { // $_GET['realname'] is the real name of the file within its location $realname = $_GET['realname']; //$_GET['filename'] is the Download Name header("Content-Disposition: attachment; filename=$_GET[filename]"); header("Content-Type: application/octet-stream"); header("Content-Length: ".filesize("mp3s/$realname")); header("Pragma: no-cache"); header("Expires: 0"); $fp = fopen("path/$filename", "r"); print fread($fp, filesize("mp3s/$realname")); fclose($fp); exit(); } ?> <a href="index.php?filename=filename.mp3&realname=realname.mp3">filename.mp3</a>
|