【发布时间】:2013-05-13 05:46:43
【问题描述】:
我正在尝试从 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 字节的文件。
更新2:
仍然没有进展,由于某种原因,服务器中的文件没有下载。除了 curl 之外,它在服务器中运行是否还有其他要求? 我还收到“2006 - MySQL 服务器已消失”,我认为这是由下载问题引起的。
【问题讨论】:
-
你为什么要用
http替换https? -
我试图解决 https url 不起作用的问题,但它并没有解决问题。
-
直接获取
https会出现什么错误? -
进行这样的替换是一个可怕的想法——如果有人想要获取例如
http://www.example.com/https-indicator.png怎么办? -
你试过libcurl吗?