在那里,我用谷歌搜索了几个小时来构建我自己的自定义卷曲功能:
输入是每件事(文件,图像,网页等的URL ......)
我有几种情况:
scenario1
$url = 'an broken link or file';
$type = null; //not important
callCurl($url,$type,10,2);
我除了函数因为if($curl = curl_init($url))
而返回false,但是没有用。(我用破坏的文件URL测试它)
scenario2
$url = 'an active url file';
$type = 'info'
callCurl($url,$type,10,2);
我除了返回文件的大小,但它首先下载文件然后给我大小!
场景3
$url = 'an active url webpage';
$type = 'content'
callCurl($url,$type,10,2);
我除了返回下载的网页以外。没问题!
scenario4
$url = 'an active url of file or images';
$type = 'content'
callCurl($url,$type,10,2);
我该如何下载文件或图片?与情景3相同吗?
这是功能:
//$type: info | content
// info: for example size of file or webpages without downloading
// content: dpwnloaded content (file/webpage/image/etc...)
function callCurl($url,$type,$timeout,$ctimeout)
{
if($curl = curl_init($url))
{
curl_setopt( $curl, CURLOPT_NOBODY, true );
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_REFERER, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );//
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT ,$ctimeout);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); //timeout in seconds
curl_setopt($curl, CURLOPT_SSLVERSION,3);
$str = curl_exec($curl);
if(curl_errno($curl))
{
echo curl_error($curl);
curl_close($curl);
return false;
}
else
{
if($type == 'info')
{
$info['mimeType'] = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
$info['size'] = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$info['path'] = parse_url($url, PHP_URL_PATH);
$info['filename'] = substr($info['path'], strrpos($info['path'], '/') + 1);
curl_close($curl);
return $info;
}
elseif($type == 'content')
{
return $str;
}
}
}
echo "This URL IS NOT ACTIVE IT IS NOT 200";
return false;
}
如何更改它以支持这些Senarios?
答案 0 :(得分:0)
对于scenario1:尝试将if(curl_errno($curl))
更改为if(0 != curl_errno($curl))
。
curl_errno将返回错误号或0(零)。
对于scenario2:您需要添加curl_setopt($ch, CURLOPT_HEADER, true)
。这并不能实际下载文件,只能检索标题。解析返回的数据时找到Content-Length
。