473,799 Members | 3,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Forcing the browser to download a music file

8 New Member
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 4597
pbmods
5,821 Recognized Expert Expert
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
Irfan12
8 New Member
Thankyou for guidance
Can you solve this problem???????? ???
Sep 15 '07 #3
Hackles
18 New Member
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 Recognized Expert Top Contributor
@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 New Member
@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 Recognized Expert Top Contributor
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 New Member
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
Irfan12
8 New Member
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 New Member
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

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

Similar topics

3
1772
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"); However, the file appears as text in the browser and I would prefer that the gray "Download this file" box pop up. How could I pull this off, or is this really more dependent on client browser settings?
3
8621
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 instead of displaying it to their browsers. This way they can save the list to a file. I know I can set it up as a txt file and let them download it that way, but right now this file is generated from a source program which I have no control over...
1
1210
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 same page they clicked "Download" button. 2) How do I force to prompt for a save file when the user clicks the button rather than try to open and read the file in the browser, which is the
4
3403
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 to open the file in the browser, so how can I either: 1. Display the Save Target as dialog box to download the a file when the file is in memory using the WebFileResponse class. 2. or simulate the right click (Save Target) from a hyperlink to a...
4
1537
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 the following code to include in the code behind: Response.ContentType = "application/vnd.ms-word" Response.AddHeader("Content-Disposition", "inline;filename=someFile.doc")
12
2921
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 the files I'm interested in were downloaded. The problem is Webalizer breaks it up by month and I want a running total. I'd also like to see the counts without having to log in to Webalizer in the first place. Not that logging in or adding the...
2
3928
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 entire piece with a spoiler in the background so users can not record them freely. The files must be secure! My original request was to have them build an application that merged the two files (spoiler and original music) into a single mp3 file and have...
7
2654
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 download script, so customers on the website can download MP3s to their harddrive (rather than merely listen to it in their browsers):
3
1842
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 possibility that I think would be viable for our situation, as changing HTTP headers isn't really feasible/desired right now (think 'expires' or 'no-cache'). Also, the file is non-HTML, so adding a 'no cache' meta tag to the file itself won't work. ...
0
10490
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10260
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10030
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9078
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7570
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6809
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.