简体   繁体   中英

Detecting the MIME type with a php upload script is not working

I am trying to detect the mime type of a audio file that is uploaded via php. I am allowing .mp3 .mp4 and .wav. For some reason it still says that it is an incorrect file type even if it is one of those types. Here is my validation code:

$allowedExts = array("wav", "mp3", "mp4", "mpeg");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "audio/wave") || ($_FILES["file"]["type"] == "audio/mp4")|| ($_FILES["file"]["type"] == "audio/mpeg"))&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {

  }

If somebody figures this out then please submit that fixed part of the code and not just a portion of it please. I appreciate any help!

A better way to check the mime type would be to let phps internal functions process the file. The content of $_FILES["file"] can be partially easily faked by an attacker. Additionaly, you have a reliable source, how your mime type is spelled.

Try finfo http://php.net/manual/de/function.finfo-open.php

$allowedMimeTypes = array('audio/wave', 'audio/mp4', 'audio/whatevermore');
$allowedExts = array('wav', 'mp3', 'mp4', 'mpeg');
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

$finfo = new finfo(FILEINFO_MIME);
$mime = $finfo->file($_FILES['file']['tmp_name']);  

if(in_array($mime, $allowedMimeTypes) && filesize($_FILES['file']['tmp_name']) < 200000 && in_array($extension, $allowedExts)) {
    echo 'yeah';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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