Issue
I am a newbie to php and wish to write a code for download that allows users to download image. Meaning i have given a download link onclick of whick the image located on the server should start downloading. i have tried various options like fopen, curl etc. but to no avail. on using curl the image downloads but does not open up in the place where it gets downloaded. It gives error saying "Cant read file header! unknown file format." Please help here's the curl code i used :
function DownloadImageFromUrl($imagepath)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL, $imagepath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
return $result;
}
$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'w');
fwrite($savefile, $imagecontent);
fclose($savefile);
Solution
You should use http headers for this
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
exit($data);
mime - MIME type of image
filename - Name of downloading file
data - the file. You can get image from other server using for example this:
$data = file_get_contents('http://www.xyz.com/back_img.png')
Answered By - Vadim Answer Checked By - Mary Flores (WPSolving Volunteer)