开发者

how to check whether file is image or video type in php version 5.2.9?

how to check whether file is image or video type in php version 5.2.9开发者_如何学JAVA


$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 extentions.


See my answer to

  • How can I check if a file is a mp3 or image file?

Example Code

 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;
 }


You can check the MIME type using the finfo_file function

Example from the help page

<?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 better checking your question, this won't work, finfo functions require PHP 5.3.0


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";
}  


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

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

I hope it was helpful for anyone.


Rather old question, but for others looking at this in the future, I would handle this like so:

function getType($file): string
{
    $mime_type = mime_content_type($file);

    return strtok($mime_type, '/');
}

This method utilises strtok to return the portion of the $mime_type string before the first /.

For example, let's say $file has a $mime_type of video/mp4, the getType method will return video.


I use this code and it works very well.

$mimeType = $request->images->getMimeType();
$fileType = explode('/', $mimeType)[0];

if it was an image, this code will give you the image word in the $fileType and if it was a video this code will give you the video word in the $fileType, then you can check on it by the if conditions.

good luck

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜