How do you initiate/force a download for files that reside externally in PHP or other language?

后端 未结 6 501
你的背包
你的背包 2021-01-25 12:54

If you have images or other files that reside externally, how do force the browser to download the link when a user click on it?

The use of \"Content-disposition: attac

相关标签:
6条回答
  • 2021-01-25 13:20

    You can use the download attribute. Just add download = 'filename.extension' to the download link:

     <a link='mysite.com/sfsf.extension' download='filenameuwant.extension'></a>
    
    0 讨论(0)
  • 2021-01-25 13:24

    I use a combination of the aforementioned "Content-Disposition" header, as well as forcing the type:

    header("Content-type: attachment/octet-stream");
    header('Content-disposition: attachment; filename="'.$filename.'"');
    
    0 讨论(0)
  • 2021-01-25 13:32

    I use a method similar to this for downloading mp4 files, could work for text files:

    $file=fopen('http://example.com/example.txt','r');
    header("Content-Type:text/plain");
    header("Content-Disposition: attachment; filename="example.txt");
    fpassthru($file);
    
    0 讨论(0)
  • 2021-01-25 13:42

    You will have to load the resource on the server first. You might want to do some caching also:

    <?php
      header("Content-disposition: attachment; filename=myfile.jpg");
      echo file_get_contents("http://host.tld/path/to/myfile.jpg");
    ?>
    
    0 讨论(0)
  • 2021-01-25 13:43

    I don't think it is possible to force a file download if you are not controlling the HTTP headers. Content-disposition: attachment is the only way I know of to accomplish this.

    Though this is probably not going to work, my only guess would be trying to combine Content-disposition with a Location header:

    Content-disposition: attachment; filename=myfile.jpg
    Location: http://www.somesite.com/myfile.jpg
    

    (it's a long shot, probably invalid and/or just bad practice)

    0 讨论(0)
  • 2021-01-25 13:44

    This is not possible. You cannot dictate a client how to handle a different resource than the currently requested one.

    You could only use a proxy to fetch the external external file and pass it to the client.

    0 讨论(0)
提交回复
热议问题