Force download from external server and rename

2019-06-20 15:36发布

问题:

I need help with a problem in a tool that Im developing.

I need to download an external file and rename it, but without using readfile(), file_get_contents() or fread() (the files are too big to read them on the server and download it again at visitor PC).

I have tried first with:

Code:

header("Location: http://www.example.com/example_download.zip");

It works for the download, but no for the example_download.zip rename.

So I have tried with readfile():

Code:

header("Content-Disposition: attachment; filename="example_download_2.zip"\n\n");
header("Content-Type: application/force-download");
    readfile("http://www.example.com/example_download.zip");
    exit;

With the above code it works well, downloading the remote file first on the server, renaming it and after sending it to the visitor with the new name, but the resources usage of this process is very high, and also the bandwidth usage.

So I'm looking for a way to generate a force-download of an external file, renaming it on the fly and generating a download with the new name but downloading directly from the source. I'ts possible?

Thanks in advance Regards

回答1:

HTML5 now allows you to do what you want through the download attribute:

<a href="http://www.example.com/example_download.zip" download="custom_filename.zip">
    Link
</a>

More Info:

http://developers.whatwg.org/links.html#attr-hyperlink-download http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download



回答2:

It's impossible for you to do this. If your php script redirected the client to some url else, then all the HTTP headers are left to the new url script to decide. You've got to download it to rename it.