PHP get content type
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 s开发者_开发技巧olution.
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);
?>
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.
精彩评论