我正在尝试使用一串文字检查2件事。首先,我想检查它是否是真正的URL。然后,如果是,我想检查该URL是否是图像。我来了this answer,它说要做以下事情:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$imageURL);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE) {
print_r("went Throught");
}
else {
print_r("Failed");
}
curl_close($ch);
无论$imageURL
是什么,我总是得到Failed
。我怎样才能实现以下目标:
if ($imageURL isRealUrl) {
// Do some code
if ($imageURL isInArrayOfImages(.png, .jpg, .GIF) {
// Do something
}
}
答案 0 :(得分:2)
你永远不能百分百肯定,但我至少会检查:
最后检查最终图像是否为重定向。 (包含404页面或默认图像文件)
user_results
停止curl将整个图像文件集retrieved by username: [<Assessment_Result(owner='<User(username ='dorisday', password='..', firstname ='Doris', lastname ='Day', email='dorisday@gmail.com')>', assessment='<Assessment(name='Becoming a Leader', text='better decisions')>')>, <Assessment_Result(owner='<User(username ='dorisday', password='..', firstname ='Doris', lastname ='Day', email='dorisday@gmail.com')>', assessment='<Assessment(name='Good work', text='working on these skills')>')>]
下载到true。
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$content_length = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$content_redirect = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT );
$imageTypes = array('image/png','image/jpeg','image/gif');
if(in_array($content_type,$imageTypes) && $content_redirect == 0 && $content_length >0){
// is a vald image
}
答案 1 :(得分:0)
您可以依赖URL标头,而不是使用cURL。虽然这不是百分之百的傻瓜证明,因为有些服务器发送了不正确的标题,但它仍然非常可靠,因为它可以处理通过脚本提供的大多数图像。唯一的另一种方法是使用getimagesize()
,但这会将整个图像下载到您的服务器。
无论如何,这是一个建议的脚本:
<?php
// URL
$url = "http://www.someurl.com/image.jpg";
// Check if URL exists
$get_headers = @get_headers($url);
if($get_headers[0] == 'HTTP/1.1 404 Not Found') {
$url_exists = false;
} else {
$url_exists = true;
}
// Check if URL is image using the same headers
if($url_exists){
if(isset($get_headers['Content-Type'])){
$type = strtolower($get_headers['Content-Type']);
$valid_image_type = array();
$valid_image_type['image/png'] = '';
$valid_image_type['image/jpg'] = '';
$valid_image_type['image/jpeg'] = '';
$valid_image_type['image/jpe'] = '';
$valid_image_type['image/gif'] = '';
$valid_image_type['image/tif'] = '';
$valid_image_type['image/tiff'] = '';
$valid_image_type['image/svg'] = '';
$valid_image_type['image/ico'] = '';
$valid_image_type['image/icon'] = '';
$valid_image_type['image/x-icon'] = '';
$valid_image_type['image/bmp'] = '';
if(isset($valid_image_type[$type])){
// URL is image
} else {
// URL isn't an image
}
}
} else {
// URL doesn't exist
}
?>