Thursday, March 31, 2011

Renaming File on another server as user downloads it [2] - using PHP

I have asked this question today already but this time I want to know if I can achieve this via PHP since Javascript wasn't up to it.

I have a link to a file on another server. If i provide this link to my users the headers are pushed out to download that file from that server.

Is there a way for me to capture those headers and file and redirect the download to the user? I would like to do this so that I can change the filename of the download since it is always 'file.zip'.

Is this possible with PHP?

Thank you for any help.

From stackoverflow
  • You can download the file to your server using curl and serve it correctly(with a Content-Disposition header). As long as you are using HTTP, there's no way to send just the header and let another server stream the content directly to the client.

    bothie : One exception: You might check, wether ftp is supported by the origin server. If yes, you could try, to set up a specialized ftp server, which only handles the control connection and let the data come from the other server. However, I doubt it's worth the effort.
  • You could do this, and you can do it in several ways.

    1) (simple) copy the file to your server, and rename it. Point your download links to this copy.
    2) (harder) Create a stub php file, called , read the file from the remote server within php, and stream the content to the script output. This will need you to set appropriate headers, etc. as well as setting up your webserver to parse through PHP.

    Seriously, I'd go with option 1. (assumes you have a legal right to serve the content, etc.)

    Abs : Would it be possible for you to go into a bit more detail with part 2 - :). I might give it a go! Thanks.
    ZombieSheep : It's been a long time since I did anything in PHP, but basically, set a content type header to match your output file; open a stream to read the remote file and then output the contents to the browser. Note : It will double you bandwidth usage as the file has to come in and then out.
    Abs : Ah I see, For bandwidth reasons, I will go with option 1!
  • Maybe you can use a script similar to the following one:

    <?php
      header("HTTP/1.1 301 Moved Permanently");
      header("Location: http://www.example.com/the_path/file.zip");
      header('Content-Disposition: attachment; filename="alternate_filename.zip"');
      exit();
    ?>
    
    bothie : Nope. Tested with GNU Wget 1.11.3, Epiphany 2.18.2 (Gecko 1.8) and Opera 9.52 for Linux: In all three cases the real filename "file.zip" was used while downloading.
    Eineki : Ops, as you pointed content-disposition doesn't apply to the external server...

0 comments:

Post a Comment