473,461 Members | 1,369 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Forcing the browser to download a music file

i dont know php & i want a script that when a user click on a mp3 hyperlink, the mp3 file start downloading instead of start playing in media player.
i got a sxript from internet search.
i am using the following code
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.           $filename = "path/to/file/filname.ext";
  3.           if(!file_exists($filename)) {
  4.               die("File does not exist!");
  5.           }
  6.           header("Pragma: public");
  7.           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  8.           header("Cache-Control: private",false);
  9.           header("Content-Disposition: attachment;   filename=\"".basename($filename)."\";" );
  10.           header("Content-Transfer-Encoding: binary");
  11.           header("Content-Type: PHP Generated Data");
  12.           header("Content-Length: ".filesize($filename));
  13.           readfile("$filename");
  14.           exit();
  15. ?>
  16.  
i have saved this code with name download.php
every time code give error message that "File does not exist!"
i have uploaded the download.php file in the same directory where the mp3 file is uploaded and i am using the folliwing hyper link code in the html file
Expand|Select|Wrap|Line Numbers
  1. <a target="_blank" href="download.php?location=ABC.mp3">downlaod ABC</a>
index.html, download.php and ABC.mp3 are in the same directory
in IE-7 it start downloading file with the name i specified in the code, but with size 27bytes, abd after opening this file in notepad i get the error "File does not exist!". BUT in Mozilla firefox it give same erroe message in a new window.

can anyone tell me what is the problem???????
Thanx
Sep 15 '07 #1
14 4479
pbmods
5,821 Expert 4TB
Heya, Irfan. Welcome to TSDN!

Changed thread title to better describe the problem (did you know that threads whose titles do not follow the Posting Guidelines actually get FEWER responses?).

Please use CODE tags when posting source code:

[CODE=php]
PHP code goes here.
[/CODE]
Sep 15 '07 #2
Thankyou for guidance
Can you solve this problem???????????
Sep 15 '07 #3
Hackles
18
i dont know php & i want a script that when a user click on a mp3 hyperlink, the mp3 file start downloading instead of start playing in media player.
i got a sxript from internet search.
i am using the following code
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.           $filename = "path/to/file/filname.ext";
  3.           if(!file_exists($filename)) {
  4.               die("File does not exist!");
  5.           }
  6.           header("Pragma: public");
  7.           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  8.           header("Cache-Control: private",false);
  9.           header("Content-Disposition: attachment;   filename=\"".basename($filename)."\";" );
  10.           header("Content-Transfer-Encoding: binary");
  11.           header("Content-Type: PHP Generated Data");
  12.           header("Content-Length: ".filesize($filename));
  13.           readfile("$filename");
  14.           exit();
  15. ?>
  16.  
i have saved this code with name download.php
every time code give error message that "File does not exist!"
i have uploaded the download.php file in the same directory where the mp3 file is uploaded and i am using the folliwing hyper link code in the html file
Expand|Select|Wrap|Line Numbers
  1. <a target="_blank" href="download.php?location=ABC.mp3">downlaod ABC</a>
index.html, download.php and ABC.mp3 are in the same directory
in IE-7 it start downloading file with the name i specified in the code, but with size 27bytes, abd after opening this file in notepad i get the error "File does not exist!". BUT in Mozilla firefox it give same erroe message in a new window.

can anyone tell me what is the problem???????
Thanx
Hmmm... it seems like in your code you have set $filename to a constant value of "path/to/file/filname.ext". Try changing your code to the following - it's better:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. if((array_key_exists('file', $_GET)) && ($fp = @fopen($_GET['file'], 'rb')) && (pathinfo($_GET['file'], PATHINFO_EXTENSION) != 'php'))
  4. {
  5.     header('Content-Disposition: attachment; filename="' . basename($_REQUEST['file']) . '";' );
  6.     header('Content-Transfer-Encoding: binary');
  7.     header('Content-Length: ' . filesize($_GET['file']));
  8.     fpassthru($fp);
  9. }
  10. else
  11. {
  12. ?><html>
  13.     <head>
  14.         <title>404 - File not found</title>
  15.     </head>
  16.     <body>
  17.         <div style="font-size:36px;">File not found</div>
  18.         <div style="font-size:12px;">The file you requested ('<?php echo $_GET['file'] ?>') could not be found.</div>
  19.     </body>
  20. </html><?php
  21. }
  22. ?>
  23.  
The code above will ensure that files that do not exist or have a php extension cannot be downloaded (otherwise, a cracker could download your source code through the download script). You could also change:
Expand|Select|Wrap|Line Numbers
  1. (pathinfo($_GET['file'], PATHINFO_EXTENSION) != 'php')
  2.  
from line 3 to:
Expand|Select|Wrap|Line Numbers
  1. (pathinfo($_GET['file'], PATHINFO_EXTENSION) == 'mp3')
  2.  
if you only want mp3s to be downloaded through your script. Then, on your downloads page, you just need to add the following HTML:
Expand|Select|Wrap|Line Numbers
  1. <a href="./download.php?file=name.mp3">Link</a>
  2.  
where "./download.php" is the path to the download script and "name.mp3" is the name of each music file.
Hope that helps, and have fun!
Sep 16 '07 #4
ak1dnar
1,584 Expert 1GB
@Irfan12
Nothing wrong with your download script. If all the files in the same Directory why don't you set the path in this way.

Some Directory
-index.html
-download.php
-ABC.mp3

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $filename = "ABC.mp3";
  3. //---------------------
  4. //---------------------
  5. ?>
  6.  
Sep 16 '07 #5
Hackles
18
@Irfan12
Nothing wrong with your download script. If all the files in the same Directory why don't you set the path in this way.

Some Directory
-index.html
-download.php
-ABC.mp3

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $filename = "ABC.mp3";
  3. //---------------------
  4. //---------------------
  5. ?>
  6.  
ajaxrand, I think Irfan12 wanted a dynamic and reusable script that can handle more than one music file - I only assume this as Irfan12 implies the functionality for multiple files:
i dont know php & i want a script that when a user click on a mp3 hyperlink, the mp3 file start downloading instead of start playing in media player.
i am using the folliwing hyper link code in the html file
Expand|Select|Wrap|Line Numbers
  1. <a target="_blank" href="download.php?location=ABC.mp3">downlaod ABC</a>
If so, then I think the code outlined in post #4 is best suited to Irfan12's needs ;).
Have fun!
Sep 16 '07 #6
ak1dnar
1,584 Expert 1GB
ajaxrand, I think Irfan12 wanted a dynamic and reusable script that can handle more than one music file - I only assume this as Irfan12 implies the functionality for multiple files:


If so, then I think the code outlined in post #4 is best suited to Irfan12's needs ;).
Have fun!
I really didn't try to discount your solution.

The Original poster has clearly mentioned about the newbieness to php. So at this point I don't like to go for any Advanced level of coding. may be other experts here also do the same. Since he is pointing his error as "File Does not Existing", I gave him the simplest way to fix it. Then If the Original poster like to learn more there he has a hope with other posts on thread. Thanks! and keep up the good works!
Sep 16 '07 #7
Hackles
18
I really didn't try to discount your solution.

The Original poster has clearly mentioned about the newbieness to php. So at this point I don't like to go for any Advanced level of coding. may be other experts here also do the same. Since he is pointing his error as "File Does not Existing", I gave him the simplest way to fix it. Then If the Original poster like to learn more there he has a hope with other posts on thread. Thanks! and keep up the good works!
Mmm... good point ajaxrand. As you can probably tell by my post count, I am relatively new to these forums and it'll take a while for me to learn how to respond well to individual cases. Thanks for the tip :)
Have fun!
Sep 16 '07 #8
Hmmm... it seems like in your code you have set $filename to a constant value of "path/to/file/filname.ext". Try changing your code to the following - it's better:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. if((array_key_exists('file', $_GET)) && ($fp = @fopen($_GET['file'], 'rb')) && (pathinfo($_GET['file'], PATHINFO_EXTENSION) != 'php'))
  4. {
  5.     header('Content-Disposition: attachment; filename="' . basename($_REQUEST['file']) . '";' );
  6.     header('Content-Transfer-Encoding: binary');
  7.     header('Content-Length: ' . filesize($_GET['file']));
  8.     fpassthru($fp);
  9. }
  10. else
  11. {
  12. ?><html>
  13.     <head>
  14.         <title>404 - File not found</title>
  15.     </head>
  16.     <body>
  17.         <div style="font-size:36px;">File not found</div>
  18.         <div style="font-size:12px;">The file you requested ('<?php echo $_GET['file'] ?>') could not be found.</div>
  19.     </body>
  20. </html><?php
  21. }
  22. ?>
  23.  
The code above will ensure that files that do not exist or have a php extension cannot be downloaded (otherwise, a cracker could download your source code through the download script). You could also change:
Expand|Select|Wrap|Line Numbers
  1. (pathinfo($_GET['file'], PATHINFO_EXTENSION) != 'php')
  2.  
from line 3 to:
Expand|Select|Wrap|Line Numbers
  1. (pathinfo($_GET['file'], PATHINFO_EXTENSION) == 'mp3')
  2.  
if you only want mp3s to be downloaded through your script. Then, on your downloads page, you just need to add the following HTML:
Expand|Select|Wrap|Line Numbers
  1. <a href="./download.php?file=name.mp3">Link</a>
  2.  
where "./download.php" is the path to the download script and "name.mp3" is the name of each music file.
Hope that helps, and have fun!


Thanks a lot Mr. Hackles.
i have found your code working on my webserver.
The only changing i have made is to remove "./" from your Html code as
Expand|Select|Wrap|Line Numbers
  1. <a href="download.php?file=name.mp3">Link</a>
  2.  
Thanks again

Now i have the problem that there is no resume support in downloading mp3 files using yours code, (i am using download accelerator for downloading purposes).
& also a problem in Mozilla firefox browser that on clicking the mp3 downlaod hyperlink in html file, download box of Mozilla firefox appears to start downloading but its ok button remains disabled.
My Html code is
Expand|Select|Wrap|Line Numbers
  1. <a target="_blank" href="download.php?file=name.mp3">link</a>
  2.  
And if use the following Html code, then Ok button of Mozilla's download box is enabled(means i can click on ok button)
Expand|Select|Wrap|Line Numbers
  1. <a href="download.php?file=name.mp3">link</a>
  2.  
means after removing target="_blank", the ok button is enabled in download box, & with target="_blank" i found the ok button disabled.
But both codes are correctly working in Internet explorer (i.e., with target="_blank" or without target="_blank")

will you please tell me the reason of resume support problem & Ok button enable/disable problem???..
Thankyou
Sep 16 '07 #9
Hackles
18
Thanks a lot Mr. Hackles.
i have found your code working on my webserver.
The only changing i have made is to remove "./" from your Html code as
Expand|Select|Wrap|Line Numbers
  1. <a href="download.php?file=name.mp3">Link</a>
  2.  
Thanks again

Now i have the problem that there is no resume support in downloading mp3 files using yours code, (i am using download accelerator for downloading purposes).
& also a problem in Mozilla firefox browser that on clicking the mp3 downlaod hyperlink in html file, download box of Mozilla firefox appears to start downloading but its ok button remains disabled.
My Html code is
Expand|Select|Wrap|Line Numbers
  1. <a target="_blank" href="download.php?file=name.mp3">link</a>
  2.  
And if use the following Html code, then Ok button of Mozilla's download box is enabled(means i can click on ok button)
Expand|Select|Wrap|Line Numbers
  1. <a href="download.php?file=name.mp3">link</a>
  2.  
means after removing target="_blank", the ok button is enabled in download box, & with target="_blank" i found the ok button disabled.
But both codes are correctly working in Internet explorer (i.e., with target="_blank" or without target="_blank")

will you please tell me the reason of resume support problem & Ok button enable/disable problem???..
Thankyou
Hello Irfan12,
The issue you have outlined with download resume support is highly common when using PHP to pass a file. Normally, a web server manages download resume by sending only the data requested through HTTP headers by the browser. While it is still possible to implement a virtual download resume support with PHP, in this instance it is far easier to use configure your web server to send a force download header for every mp3 file. This approach has several advantages:
  1. It does not require PHP, so your HTML anchor code can simply link to the media file
  2. It provides complete support for command headers by the web server (so download resuming works)
  3. It will work for every specified file
For an Apache server, the code is:
Expand|Select|Wrap|Line Numbers
  1. LoadModule headers_module modules/mod_headers.so
  2. <FilesMatch "\.(?i:mp3)$">
  3.     ForceType application/octet-stream
  4.     Header set Content-Disposition attachment
  5. </FilesMatch>
  6.  
The first line enables a plugin called mod_headers, which essentially allows Apache to override default headers, and should always be put in the httpd.conf file. The second, third and fourth linse defines a rule for all files ending with mp3 case insensitive (replace this with your media file's extension). Place these lines in your httpd.conf if you want all mp3s to be forced to automatically download, or place it in a .htaccess file within a particular directory to have it work exclusively in that directory. (Note: you will need the mod_headers plugin for this to work, but this plugin is generally distributed with most Apache packages.) Let me know if you need further help with this.

As to your second issue regarding the OK button, I am not completely certain - either it is a Firefox bug, or a security implementation. Either way, it seems toggling the options from 'Save to disk' to another option (like 'Open with') and back to 'Save to disk' enables the OK button.

All the best, and have fun!
Sep 17 '07 #10
Hackles
18
Just an amendment to the last post: As far as I know of, it is impossible to set the FilesMatch rule for a specific directory (I've tried .htaccess, nesting within a Directory rule, even adding a path to the regex for the FilesMatch rule, but it doesn't seem to work). I guess that'd be a slight downside, not being able to control which directory falls under direct download control.
An alternative (that achieves the same result) is:
Expand|Select|Wrap|Line Numbers
  1. AddType application/octet-stream .mp3
  2.  
The benefit of the above handler (which goes in httpd.conf) is that you don't need mod_headers enabled.
Note that any changes to httpd.conf will require a server restart.
Hope this helps...
Have fun!
Sep 17 '07 #11
Thanks for reply,
but as i said in the start that i dont know even PHP, than how can i understand what is to change and where to change/add your give Code.
i am using linux webserver, kindly tell me the simplest way so that there may be a resume support in downloading,
In adddation to my last post, i want to tell that Mozilla firefox's download box have the resume support, but download accelerator dont have resume support.

thakyou
Sep 17 '07 #12
Just an amendment to the last post: As far as I know of, it is impossible to set the FilesMatch rule for a specific directory (I've tried .htaccess, nesting within a Directory rule, even adding a path to the regex for the FilesMatch rule, but it doesn't seem to work). I guess that'd be a slight downside, not being able to control which directory falls under direct download control.
An alternative (that achieves the same result) is:
Expand|Select|Wrap|Line Numbers
  1. AddType application/octet-stream .mp3
  2.  
The benefit of the above handler (which goes in httpd.conf) is that you don't need mod_headers enabled.
Note that any changes to httpd.conf will require a server restart.
Hope this helps...
Have fun!


Thanks for your code,
i am using download accelerator to do download my files but it gives error message in start of downloading that "resume not supported". means if user lost his connection than it is not possible to start/resume download from the broken state. Means that if a user is downloading 3 mb file, and after 2 mb of download if user lost internet connection, or due to power failure, than the user will lost 2 mb, and user must start downlaoding from the beginning.
Actualy, when i use download.php for forced download than there is no resume supprt, but when i use normal downloading (means to right click on link and select "save target as...") than there is a resume support, but by using download.php (above given code) there is no resume support.
Kindly tell me is there any problem in the above code, or what should i do?????
Thankyou
Sep 21 '07 #13
hi all,

i have been following this thread with much interest, and it works fine, except for one thing.......

when downloading it prefixes the file with .html. so for example, a fill downloads as mymusic.mp3.html

how can i get it to scrap the HTML bit?
Jul 2 '08 #14
pbmods
5,821 Expert 4TB
Heya, whiteyoh.

Check out this article (http://www.phpit.net/code/force-download/).
Jul 3 '08 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: D. Alvarado | last post by:
Hello, I have a page that generates a text file (but writes the file with the ".csv" extension) and then I redirect the user so he can save the file header("Location: $my_csv_file"); ...
3
by: Julie | last post by:
I have an html file where I display name,address,zip. It is one per line so it is basicall a list of addresses. But I would like ie6 to force the download prompt of this long list of names...
1
by: Do | last post by:
Hi, My issue is twofold. 1) How do I invoke a "save file" action when a user clicks a button. In classic ASP, I used to response.redirect to file path. But I want to keep the user on the...
4
by: randmCP | last post by:
Hi and thanks in advanced for you help. I am working on a file-distribution asp.net application. Users click on a custom grid column to download files stored on a SQL DB. The client does not want...
4
by: teeBull | last post by:
Hi all, We'd like to take advantage of code we already have for transforming XML into HTML (using XSLT) for our users to save the HTML as an MS Word document locally. I've dug around and found...
12
by: devospice | last post by:
Hi, I'm trying to create a download counter for individual files on a web site and I'm not sure how to do this. Right now I'm using Webalizer to just read the log files and see how many times...
2
by: FlashForumKB | last post by:
Here is a chance for you to make my developers look bad. I have hired these guys to development my website which, in part, has music demos available to my users. These demos must include the...
7
by: lawrence k | last post by:
I've got a music studio for a client. Their whole studio is run with Macintosh computers. Macintosh computers allow file names to have open white spaces, such as "animal hospital.mp3". I have a...
3
by: Don | last post by:
Is it possible to create a link which will cause either A) the server to serve a fresh copy of a file or B) the browser to "refresh" the copy of the file. Doing it via a link is the only...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.