问题
I set it up so a user can download an image with the click of a button if it's hosted on my site, but it doesn't work for external images. Is it possible to do this with external images (using the URL) without first copying it to a folder on my servers?
This is what I use for images on my own site.
$str = $_GET['image'];
$img_name = substr(strrchr($str, '/'), 1);
$image = "../u/i/".$img_name;
if (file_exists($image)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($image));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($image));
ob_clean();
flush();
readfile($image);
exit();
}
回答1:
As you can see on http://php.net/manual/en/function.readfile.php you can use external URLs.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
It's a PHP setting: http://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
(The code doesn't need change then.)
来源:https://stackoverflow.com/questions/10926511/allow-user-to-download-external-image-using-php