Forcing the browser to download a music file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Irfan12
    New Member
    • Sep 2007
    • 8

    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
    [code=php]
    <?php
    $filename = "path/to/file/filname.ext";
    if(!file_exists ($filename)) {
    die("File does not exist!");
    }
    header("Pragma: public");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false) ;
    header("Content-Disposition: attachment; filename=\"".ba sename($filenam e)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: PHP Generated Data");
    header("Content-Length: ".filesize($fil ename));
    readfile("$file name");
    exit();
    ?>
    [/code]
    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
    [code=html]
    <a target="_blank" href="download. php?location=AB C.mp3">downlaod ABC</a>[/code]

    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
    Last edited by pbmods; Sep 15 '07, 09:29 PM. Reason: Added [CODE] tags.
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    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:

    &#91;CODE=ph p]
    PHP code goes here.
    &#91;/CODE]

    Comment

    • Irfan12
      New Member
      • Sep 2007
      • 8

      #3
      Thankyou for guidance
      Can you solve this problem???????? ???

      Comment

      • Hackles
        New Member
        • Sep 2007
        • 18

        #4
        Originally posted by Irfan12
        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
        [code=php]
        <?php
        $filename = "path/to/file/filname.ext";
        if(!file_exists ($filename)) {
        die("File does not exist!");
        }
        header("Pragma: public");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false) ;
        header("Content-Disposition: attachment; filename=\"".ba sename($filenam e)."\";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Type: PHP Generated Data");
        header("Content-Length: ".filesize($fil ename));
        readfile("$file name");
        exit();
        ?>
        [/code]
        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
        [code=html]
        <a target="_blank" href="download. php?location=AB C.mp3">downlaod ABC</a>[/code]

        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:
        [code=php]
        <?php

        if((array_key_e xists('file', $_GET)) && ($fp = @fopen($_GET['file'], 'rb')) && (pathinfo($_GET['file'], PATHINFO_EXTENS ION) != 'php'))
        {
        header('Content-Disposition: attachment; filename="' . basename($_REQU EST['file']) . '";' );
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . filesize($_GET['file']));
        fpassthru($fp);
        }
        else
        {
        ?><html>
        <head>
        <title>404 - File not found</title>
        </head>
        <body>
        <div style="font-size:36px;">Fil e not found</div>
        <div style="font-size:12px;">The file you requested ('<?php echo $_GET['file'] ?>') could not be found.</div>
        </body>
        </html><?php
        }
        ?>
        [/code]
        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:
        [code=php]
        (pathinfo($_GET['file'], PATHINFO_EXTENS ION) != 'php')
        [/code]
        from line 3 to:
        [code=php]
        (pathinfo($_GET['file'], PATHINFO_EXTENS ION) == 'mp3')
        [/code]
        if you only want mp3s to be downloaded through your script. Then, on your downloads page, you just need to add the following HTML:
        [code=html]
        <a href="./download.php?fi le=name.mp3">Li nk</a>
        [/code]
        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!
        Last edited by Hackles; Sep 16 '07, 05:29 AM. Reason: Added further information

        Comment

        • ak1dnar
          Recognized Expert Top Contributor
          • Jan 2007
          • 1584

          #5
          @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

          [CODE=php]
          <?php
          $filename = "ABC.mp3";
          //---------------------
          //---------------------
          ?>
          [/CODE]

          Comment

          • Hackles
            New Member
            • Sep 2007
            • 18

            #6
            Originally posted by ajaxrand
            @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

            [CODE=php]
            <?php
            $filename = "ABC.mp3";
            //---------------------
            //---------------------
            ?>
            [/CODE]
            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:
            Originally posted by Irfan12
            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.
            Originally posted by Irfan12
            i am using the folliwing hyper link code in the html file
            [code=html]
            <a target="_blank" href="download. php?location=AB C.mp3">downlaod ABC</a>[/code]
            If so, then I think the code outlined in post #4 is best suited to Irfan12's needs ;).
            Have fun!

            Comment

            • ak1dnar
              Recognized Expert Top Contributor
              • Jan 2007
              • 1584

              #7
              Originally posted by Hackles
              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!

              Comment

              • Hackles
                New Member
                • Sep 2007
                • 18

                #8
                Originally posted by ajaxrand
                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!

                Comment

                • Irfan12
                  New Member
                  • Sep 2007
                  • 8

                  #9
                  Originally posted by Hackles
                  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:
                  [code=php]
                  <?php

                  if((array_key_e xists('file', $_GET)) && ($fp = @fopen($_GET['file'], 'rb')) && (pathinfo($_GET['file'], PATHINFO_EXTENS ION) != 'php'))
                  {
                  header('Content-Disposition: attachment; filename="' . basename($_REQU EST['file']) . '";' );
                  header('Content-Transfer-Encoding: binary');
                  header('Content-Length: ' . filesize($_GET['file']));
                  fpassthru($fp);
                  }
                  else
                  {
                  ?><html>
                  <head>
                  <title>404 - File not found</title>
                  </head>
                  <body>
                  <div style="font-size:36px;">Fil e not found</div>
                  <div style="font-size:12px;">The file you requested ('<?php echo $_GET['file'] ?>') could not be found.</div>
                  </body>
                  </html><?php
                  }
                  ?>
                  [/code]
                  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:
                  [code=php]
                  (pathinfo($_GET['file'], PATHINFO_EXTENS ION) != 'php')
                  [/code]
                  from line 3 to:
                  [code=php]
                  (pathinfo($_GET['file'], PATHINFO_EXTENS ION) == 'mp3')
                  [/code]
                  if you only want mp3s to be downloaded through your script. Then, on your downloads page, you just need to add the following HTML:
                  [code=html]
                  <a href="./download.php?fi le=name.mp3">Li nk</a>
                  [/code]
                  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
                  [code=html]
                  <a href="download. php?file=name.m p3">Link</a>
                  [/code]

                  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
                  [code=html]
                  <a target="_blank" href="download. php?file=name.m p3">link</a>
                  [/code]

                  And if use the following Html code, then Ok button of Mozilla's download box is enabled(means i can click on ok button)
                  [code=Html]
                  <a href="download. php?file=name.m p3">link</a>
                  [/code]

                  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

                  Comment

                  • Hackles
                    New Member
                    • Sep 2007
                    • 18

                    #10
                    Originally posted by Irfan12
                    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
                    [code=html]
                    <a href="download. php?file=name.m p3">Link</a>
                    [/code]

                    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
                    [code=html]
                    <a target="_blank" href="download. php?file=name.m p3">link</a>
                    [/code]

                    And if use the following Html code, then Ok button of Mozilla's download box is enabled(means i can click on ok button)
                    [code=Html]
                    <a href="download. php?file=name.m p3">link</a>
                    [/code]

                    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:
                    Code:
                    LoadModule headers_module modules/mod_headers.so
                    <FilesMatch "\.(?i:mp3)$">
                    	ForceType application/octet-stream
                    	Header set Content-Disposition attachment
                    </FilesMatch>
                    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!
                    Last edited by Hackles; Sep 17 '07, 08:31 AM. Reason: Minor adjustments

                    Comment

                    • Hackles
                      New Member
                      • Sep 2007
                      • 18

                      #11
                      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:
                      Code:
                      AddType application/octet-stream .mp3
                      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!

                      Comment

                      • Irfan12
                        New Member
                        • Sep 2007
                        • 8

                        #12
                        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

                        Comment

                        • Irfan12
                          New Member
                          • Sep 2007
                          • 8

                          #13
                          Originally posted by Hackles
                          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:
                          Code:
                          AddType application/octet-stream .mp3
                          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

                          Comment

                          • whiteyoh
                            New Member
                            • Jun 2008
                            • 13

                            #14
                            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.htm l

                            how can i get it to scrap the HTML bit?

                            Comment

                            • pbmods
                              Recognized Expert Expert
                              • Apr 2007
                              • 5821

                              #15
                              Heya, whiteyoh.

                              Check out this article (http://www.phpit.net/code/force-download/).

                              Comment

                              Working...