简体   繁体   English

检查文件是否是PHP中的音频文件

[英]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.我正在编写代码来上传音频文件(可以是任何格式。mp3、mp4、.wav 等等...)我不想写所有 mime 类型的所有条件,然后检查上传的文件以验证哑剧类型。 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!谢谢!

All the audio files format has "audio/" common in MIME Type. 所有音频文件格式在MIME类型中均具有"audio/" 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. 因此,我们可以检查$_FILES['file']['mime_type']并应用preg_match()来检查此"audio/"类型是否存在"audio/"

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

You can choose common audio extensions or all extensions into an array one time. 您可以一次将通用音频扩展或所有扩展选择到一个阵列中。 Then validate through that array you have. 然后通过您拥有的阵列进行验证。

You can see with "console.log(document.getElementById("your_file").files[0])" one of the data from console is "type: audio/mpeg".您可以通过“console.log(document.getElementById("your_file").files[0])”看到来自控制台的数据之一是“type: audio/mpeg”。 So you can validations with type of ur file like this:所以你可以像这样使用你的文件类型进行验证:

$format_audio = $_FILES['your_file']['type'];
if ($format_audio != "audio/mpeg") {
   // your command
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM