This was asked before, but nothing works for me:
getimagesizeis not recommended to use for this purpose by the PHP manual.get_headersas in this example don't find any headers.exif_imagetyperefuses to check a remote URL.- I have also tried one 'curl' example (not sure which), and it didn't work for me either.
What I want to do: If the URL is pointing at an image, present it as <img>. Otherwise <a>.
Edit1: Based on the solution linked above, I extract the extension. It works, but very unreliable:
if(filter_var($url, FILTER_VALIDATE_URL))
{
$extension = strtolower(strtok(pathinfo($url, PATHINFO_EXTENSION),'?'));
$valid_image_type=array();
$valid_image_type['png']='';
$valid_image_type['jpg']='';
$valid_image_type['jpeg']='';
$valid_image_type['gif']='';
$valid_image_type['tif']='';
$valid_image_type['tiff']='';
$valid_image_type['svg']='';
$valid_image_type['ico']='';
$valid_image_type['icon']='';
$valid_image_type['x-icon']='';
if(isset($valid_image_type[$extension])){
$base = "<img src=\"$url\" >";
}
else
{
$base = "<a href=\"$url\">...</a>";
}
}
else
{
// Plain text
}
switch is a multiple OR, so the code above could be simplified. The strtok removes the arguments following the extension:
switch (strtolower(strtok(pathinfo($url, PATHINFO_EXTENSION),'?'))) {
case 'png':
case 'jpg':
case 'jpeg':
case 'gif':
case 'tif':
case 'tiff':
case 'svg':
case 'ico':
case 'icon':
case 'x-icon':
// URL is an image
break;
default:
// URL is not an image
}