我正在尝试创建一个与URL一起使用的简单is_file类型函数:
function isFileUrl($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // don't want it rendered to browser
curl_exec($ch);
if(curl_errno($ch)){
$isFile = false;
}
else {
$isFile = true;
}
curl_close($ch);
return $isFile;
}
if(isFileUrl('https://www.google.com/images/srpr/logo4w.png')==true){
echo 'TRUE';
} else {
echo 'FALSE';
}
在删除curl_setopt
的情况下工作,但将内容(图像 url)呈现到浏览器,这是我不想要的。我错过了什么?我已经检查了这个类似的线程,但无法让它在我的上下文中工作。谢谢。
为什么不使用 get_headers() 函数?它是为这些事情而设计的。
简单示例如下所示:
function isFile($url) {
$headers = get_headers($url);
if($headers && strpos($headers[0], '200') !== false) { //response code 200 means that url is fine
return true;
} else {
return false;
}
}
您还可以检查所需的内容类型或任何其他标头。
我认为你想要的是一个HTTP标头检查,看看它是否是一个有效的(200)url,并且它与图像相关(内容类型===图像/jpg,图像/png等)。以下代码可能是一个开始:
function getHTTPStatus($url) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => false
));
curl_exec($ch);
$http_status = curl_getinfo($ch);
return $http_status;
}
$img = getHTTPStatus($url);
$images = array('image/jpeg', 'image/png', 'etc');
if($img['http_code'] === 200 && in_array($img['content_type'], $images)) {
//it is an image, do stuff
}
(自我回答/总结)
德拉戈斯特和埃纳普佩的答案都有效。根据 Enapupe 的回答,我将其包装成一个包罗万象的函数,并添加了一个可选的文件类型参数。希望它对某人有所帮助...
function isFileUrl($url, $type=''){
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => false
));
curl_exec($ch);
$gh = curl_getinfo($ch);
if($type!==''){
// add types here (see http://reference.sitepoint.com/html/mime-types-full for list)
if($type=='img'){
$typeArr = array('image/jpeg', 'image/png');
}
elseif($type=='pdf'){
$typeArr = array('application/pdf');
}
elseif($type=='html'){
$typeArr = array('text/html');
}
if($gh['http_code'] === 200 && in_array($gh['content_type'], $typeArr)){
$trueFalse = true;
}
else {
$trueFalse = false;
}
}
else {
if($gh['http_code'] === 200){
$trueFalse = true;
}
else {
$trueFalse = false;
}
}
return $trueFalse;
}
//test - param 1 is URL, param 2 (optional) can be img|pdf|html
if(isFileUrl('https://www.google.com/images/srpr/logo4w.png', 'img')==true){
// do stuff
echo 'TRUE';
}
else {
echo 'FALSE';
}