How to check if a file is an image or video type in PHP version 5.2.9?

how to check if a file is an image or video type in php version 5.2.9

+8
php
source share
5 answers
$mime = mime_content_type($file); if(strstr($mime, "video/")){ // this code for video }else if(strstr($mime, "image/")){ // this code for image } 

Should work for most file extensions.

+17
source share

See my answer to

  • How to check if an mp3 file or image file?

Code example

  function getMimeType($filename) { $mimetype = false; if(function_exists('finfo_fopen')) { // open with FileInfo } elseif(function_exists('getimagesize')) { // open with GD } elseif(function_exists('exif_imagetype')) { // open with EXIF } elseif(function_exists('mime_content_type')) { $mimetype = mime_content_type($filename); } return $mimetype; } 
+6
source share

You can check the MIME type with finfo_file function

Help page example

 <?php $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension foreach (glob("*") as $filename) { echo finfo_file($finfo, $filename) . "\n"; } finfo_close($finfo); ?> 

EDIT : after checking your check this will not work, finfo functions require PHP 5.3.0

+3
source share
 if(isset($_FILES['my_file'])) { $mime = $_FILES['my_file']['type']; if(strstr($mime, "video/")){ $filetype = "video"; }else if(strstr($mime, "image/")){ $filetype = "image"; }else if(strstr($mime, "audio/")){ $filetype = "audio"; } 
+2
source share

I use the following code, which IMO is more universal than in the first and most voted answer:

 $mimeType = mime_content_type($filename); $fileType = explode('/', $mimeType)[0]; 

I hope this was helpful to everyone.

0
source share

All Articles