Search code examples
phpfile-upload

check if the file is audio file in PHP


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!


Solution

  • 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.

    if(preg_match('/audio/i', $_FILES['file']['mime_type']))
        echo 'It is an Audio File';
    

    OR

    if(explode("/", $_FILES['file']['mime_type'])[0] == "audio")
        echo 'It is an Audio File';