check if the file is audio file in PHP

2019-04-08 16:09发布

I'm writing code to upload audio file (could be in any format .mp3, mp4, .wav and many more...) I dont want to write all the conditions for all the mime types and then check uploaded file to validate the mime type. Because, I want to ACCEPT ALL the audio files(not just one or two formats).

So, is there any simple way to check whether the file is audio or not?

Thank you!

4条回答
Summer. ? 凉城
2楼-- · 2019-04-08 16:37

All the audio files format has "audio/" common in MIME Type. So, we can check the $_FILES['file']['mime_type'] and apply a preg_match() to check if "audio/" exists in this mime type or not.

查看更多
小情绪 Triste *
3楼-- · 2019-04-08 16:41

You can choose common audio extensions or all extensions into an array one time. Then validate through that array you have.

查看更多
【Aperson】
4楼-- · 2019-04-08 16:51

You must know all mime type's of audio and video, this is the list of audio & video mimes

<?php
$audio_mime_types = array(
    'audio/mpeg'
);
?>

and then check your file by using this

$path = $_FILES['your_files_input']['name'];
$ext = mime_content_type($path);

if(!empty($audio_mime_types[$ext])){
   return "This is audio video file";
}
查看更多
Bombasti
5楼-- · 2019-04-08 16:52

Here is the simple function

<?php
if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {

        $mime_types = array(

            // audio/video
            'mp3' => 'audio/mpeg',

        );

        $ext = strtolower(array_pop(explode('.',$filename)));
        if (array_key_exists($ext, $mime_types)) {
            return "THIS IS AUDIO FILES";
        }
        else {
            return 'application/octet-stream';
        }
    }
}
?>
查看更多
登录 后发表回答