如何检测URL是否引用图像


How to detect whether a URL refers to an image or not

我想知道如何检测添加到回复字段中的URL是否是图像URL。

如果它是一个图像URL,那么我想在回复中插入一个img标记,如果不是,那么我只想插入一个锚标记。

使用以下代码:

<?PHP
$URL = 'https://s3.amazonaws.com/wrapbootstrap/live/products/icons/WB0XLB528.jpg';
$isImage = false;
$header = get_headers( $URL , true );
if( preg_match( '!image/*!si' , $header['Content-Type'] ) )
{
    $isImage = true;
}
var_dump( $isImage );
?>

如果is $isImage为真,则您的链接是图像

编辑:

使用get_headers函数获取url的头,如果Content-Type是image/png或image.jpg或image.bmp或etc(image/*),则在头中url返回图像。

$filename = 'insert_url_here';
$contents = file_get_contents($filename);
$finfo=finfo_open(FILEINFO_MIME_TYPE)
if($finfo == "image/png" || $finfo == "image/jpg" || $finfo == "image/bmp"){
    // add mimetypes to test for
    echo "<img src='" . $filename . "' alt='image'></img>";
}
else{
    echo "<a href='" . $filename . "'></img>";
}

试试这个:

$url = "http://wewwefwe.com/image.png";
$image_extentions = array('gif', 'jpg', 'jpeg', 'png', 'tiff');
$url = explode('.', $url);
$extention = end($url);
if(in_array($extention, $image_extentions)){
    echo "Image";
}else{
    echo "Not an Image";
}