I'm trying to download an image file programatically from within PHP and then treat it locally.
Edited: the previous function was replace by the one suggested below.
I have this function:
function downloadFile ($url, $path) {
$result = false;
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_exec( $ch ) ;
if(!curl_errno($ch))
{
$type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ( stripos($type, 'image') !== FALSE )
{
// probably image
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$fp=fopen($path,'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
fclose($fp);
if ( exif_imagetype($path) != FALSE )
{
// 100% image
$result = true;
}
else
{
// not an image
unlink($path);
}
}
}
curl_close($ch);
return $result;
}
What I really need is a function which is robust and can deal with any type of image and also if the url is invalid and there is no image.
update:
I changed my downloadFile function with the one suggested below. On my local computer it works great, but on my server it fails :/ I'm having some files downloaded with 0 bytes.
update2:
Still no progress, in the server for some reason the files are not downloaded. Besides having curl, is there any other requirements for it to ran in the server? I get also a "2006 - MySQL server has gone away", which I believe is caused by the download problem.