PHP: How to Save Image From Web (Remote Image)

June 01, 2011

$remoteFile can be a link to any file, not only an image.

Please keep in mind that $localFile should have same extension as $remoteFile.

<?
$remoteFile
='http://chart.apis.google.com/chart?chs=150x150&cht=qr&chld=L|0&chl=http://superiorwebsys.com'
;
$localFile=$_SERVER['DOCUMENT_ROOT'].'/tmp/image2.png'
;
saveFileFromTheWeb($remoteFile,$localFile
);
function
saveFileFromTheWeb($remoteFile,$localFile
){
   $ch = curl_init
();
   $timeout = 0
;
   curl_setopt ($ch, CURLOPT_URL, $remoteFile
);
   curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout
);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1
);
   curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1
);
   $image = curl_exec($ch
);
   curl_close($ch
);
   $f = fopen($localFile, 'w'
);
   fwrite($f, $image
);
   fclose($f
);
}
?>

Thanks to rgnelson for the question asked here: Generate QR Code with PHP Using Google API