1

I have problem in download image from url,

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

in this code file is saving in my server folder .but i needed without saving in my server it needs to be download to user.

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
elango
  • 143
  • 7

2 Answers2

0

Use application/octet-stream instead of image/jpg:

If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog. — 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');

if you want to download the file onto your webserver(and save it), just use copy()

copy($url, 'myfile.png');
Community
  • 1
  • 1
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
0

set the correct header and echo it out instead of file_put_contents

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

header('Content-Disposition: attachment; filename:image.jpg');
echo file_get_contents($url);
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • Not working.. $url = 'http://chart.googleapis.com/chart?cht=qr&chs=150x150&chl=asasdasdsasd&choe=UTF-8&chld=H|0'; header('Content-Disposition: attachment; filename:image.png'); echo file_get_contents($url); – elango Aug 13 '13 at 12:56