tags:

views:

66

answers:

2

I was wondering if there is a way to find out if a given string is an image e.g.

$a = 'php';// output false
$b = 'jpg';// output true
$c = 'js'; // output false
$d = 'png';// output : true

I know it can be done by checking it against an array but I am just wondering if there is a better solution.

+2  A: 

I found this: http://www.php.net/manual/en/function.finfo-file.php.

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    if substr(finfo_file($finfo, $filename), 0, 6) == "image"
        printf("%s is an image file.", $filename);
}
finfo_close($finfo);
?>

Also, like Pekka's comment says, you are mixing up your title and your question. If you want to find out the content type of a particular file, you can use the code snippet I provided.

Otherwise, it just sounds like you want to see if an extension to a file is indicative of it being an image. Then, you would just want to test for the existence of the string in an array of pre-defined extensions:

<?php

$imageExtensions = array('jpg', 'gif', 'png', ....);
$someFileExtension = 'jpg';

if in_array($someFileExtension, $imageExtensions)
    printf("%s is an extension indicative of an image file.", $someFileExtension);

?>
indienick
the truth is either one would work... I knew about the second option... which is that I should go for that one as it may be quicker than the `finfo` option (which needs to install it as php extension).
Val
@Val In order to identify the type of a file from a user upload, you should _always_ check the mime type. Checking the file extension in this case is a security issue and unreliable.
w3d
+1  A: 

http://php.net/manual/en/function.exif-imagetype.php returns the image type of a file or false if it is not an image.

http://pel.sourceforge.net/ is a pear package.

brian_d