从另一个服务器URL下载图像而不保存在我的服务器文件夹中

时间:2013-07-31 10:52:24

标签: php image download

我在网址下载图片时遇到问题,

$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));

在此代码文件中保存在我的服务器文件夹中。但我需要不保存在我的服务器中,它需要下载到用户。

2 个答案:

答案 0 :(得分:0)

使用application/octet-stream代替image / jpg:

如果在具有application / octet-stream内容类型的响应中使用[Content-Disposition]标头,则隐含的建议是用户代理不应显示响应,而是直接输入`save response as。 ..''对话框。 — RFC 2616 – 19.5.1 Content-Disposition

EDIT

function forceDownloadQR($url, $width = 150, $height = 150) {
    $url    = urlencode($url);
    $image  = 'http://chart.apis.google.com/chart?chs='.$width.'x'.$height.'&cht=qr&chl='.$url;
    $file = file_get_contents($image);
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=qrcode.png");
    header("Cache-Control: public");
    header("Content-length: " . strlen($file)); // tells file size
    header("Pragma: no-cache");
    echo $file;
    die;
}

forceDownloadQR('http://google.com');

如果您要将文件下载到您的网络服务器上(并保存),请使用copy()

copy($url, 'myfile.png');

答案 1 :(得分:0)

设置正确的标头并将其回显而不是file_put_contents

$url = 'http://example.com/image.php';

header('Content-Disposition: attachment; filename:image.jpg');
echo file_get_contents($url);