check if the file is audio file in PHP

2019-04-08 15:56发布

问题:

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!

回答1:

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.



回答2:

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


回答3:

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



回答4:

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