我正在尝试从PHP中以编程方式下载一个图像文件,然后在本地处理它。
编辑:以前的职能由以下提议的职能取代。
我的职能是:
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;
}我真正需要的是一个功能,它是健壮的,可以处理任何类型的图像,如果url是无效的并且没有图像。
更新:
我用下面建议的方法更改了我的downloadFile函数。在我的本地计算机上,它工作得很好,但是在我的服务器上它失败了:/我下载的一些文件只有0字节。
update2:
仍然没有进展,在服务器中,由于某些原因,文件没有下载。除了有卷曲之外,在服务器中运行它还有其他要求吗?我还得到了一个"2006 - MySQL服务器已经消失“,我相信这是由下载问题造成的。
发布于 2013-05-24 03:30:57
最后,这是最有效的下载功能:
/*
* This function downloads the image to the plugin/topposts/temp folder
*/
function downloadFile ($url, $path) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$con = curl_exec($ch);
curl_close($ch);
file_put_contents($path, $con);
return true;
}不检查类型,但有效。谢谢你的帮助。
发布于 2013-05-13 06:24:54
使用cURL。
此函数也检查图像的url。返回true/false (图像或否)。
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;
}请求:
if ( !downloadFile($url, $path) )
{
// an error
} 发布于 2013-05-13 06:21:31
我认为您需要安装openssl并使用PHP进行配置。
https://stackoverflow.com/questions/16515550
复制相似问题