drl2051 2015-04-05 08:02
浏览 65
已采纳

验证音频文件

Is there any built-in function in PHP to validate an audio file except comparing MIME types, which can easily be invalid, because who says user uploads it only using a web-browser, anyone can make custom uploader sending let's say MIME type as audio/mpeg even though it's an EXE.

Or do I really have to compare magic numbers of each file?

Let's say I would accept only mp3,ogg,wav,mka,wma,mp4 (m4a) to be uploaded.

  • 写回答

1条回答 默认 最新

  • doob0526 2015-04-05 08:19
    关注

    You can use the FileInfo extension. The mime types here are not provided by the client; they are figured out by the FileInfo extension. The mime types are figured out by looking at the contents of the file (often the first few bytes of the file, but some file formats need a little more analysis).

    So, if a file is recognized as an audio file then it cannot be an executable. It may be an executable with an audio file signature, but audio players will not execute it; they will just read the file and treat it as audio data (and most likely give you an error saying that the file is corrupted).

    I am not sure to what extent the extension looks at the file, but I a pretty sure it does as little as it can get away with. In other words, it most likely does not go through the entire file, checking that it is 100% valid. In order to do that to all the file formats you are allowing, you would need more heavy-duty programs, and probably at least a dedicated server. Unless you absolutely need to be 100% sure of a file's validity, doing a cursory check, like here, should be enough.

    $file = '/path/to/file.mp3';
    
    $info = new finfo(FILEINFO_MIME);
    $type = $info->buffer(file_get_contents($file));
    
    switch ($type) {
        case 'audio/mpeg':
            echo 'MP3!';
        break;
        case 'audio/ogg':
            echo 'OGG!';
        break;
        case 'audio/wav':
            echo 'WAV!';
        break;
        case 'audio/x-matroska':
            echo 'MKA!';
        break;
        case 'audio/mp4':
            echo 'MP4!';
        break;
        default:
            die('Format not supported!');
        break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么