Skip to content
Advertisement

how to check if a file is either a video type, image type or a document type in php

I am trying to perform an action if a certain file is of a certain type; image, video or document.

What I have tried so far:

if(preg_match("/.(mp4|mov)$/", $filename)) and

$videoType = array('mp4', 'mov');
$filename = $_FILES['file']['tmp_name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

None of the above work and the ISSUE is mainly on identifying the video type

full code:

$info = getimagesize($_FILES['file']['tmp_name']);
$videoTypes = array('mp4', 'mov');
$imageTypes = array('gif', 'jpg', 'png');
$filename = $_FILES['file']['tmp_name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

if($info[2] == IMAGETYPE_GIF || $info[2] == IMAGETYPE_JPEG || $info[2] == IMAGETYPE_PNG) {
// perform action with image types
...
} else if(in_array($ext, $videoTypes)) {
// perform action with video types
...
} else {
// perform action with doc types
...
}

reference: Check file extension in upload form in PHP

Advertisement

Answer

Try use mime_content_type.

<?php

$filepath = '/tmp/Video.mp4';
$extensions = ['video' => ['mp4'], 'image' => ['jpg']];
$mime_types = ['video' => ['video/mp4'], 'image' => ['image/jpeg']];

if(file_exists($filepath)) {

    $extension = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));

    // Video
    if(in_array($extension, $extensions['video'])) {
       
        $mime = mime_content_type($filename);

        if($mime !== false) {

            if(in_array($mime, $mime_types['video'])) {

                // do something

            }

        }

    }

}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement