2

I have a code part that checks if:

($_FILES["fileToUpload"]["type"] == "image/gif" || $_FILES["fileToUpload"]["type"] == "image/jpeg" || $_FILES["fileToUpload"]["type"] == "image/png")

What can I replace 'image/gif' with to make it filter pdf's and also mp3s?

mario
  • 144,265
  • 20
  • 237
  • 291
Shawn
  • 933
  • 4
  • 18
  • 29

4 Answers4

5

See list of MIME types.

You could write your code easier to read like this:

$mime_filter = array(
  'image/gif', 'image/jpeg', 'image/png', 
  'application/pdf',
  'audio/mpeg', 'audio/mpeg3', 'audio/x-mpeg', 'audio/x-mpeg-3');

if (in_array($_FILES["fileToUpload"]["type"], $mime_filter)) {
  // ...
Czechnology
  • 14,832
  • 10
  • 62
  • 88
5

Not exactly an answer to your question, but rather an aside:

Checking the type value does not tell you anything at all. This value is produced by the browser and is not checked by PHP on the server side (many similar questions here on SO have answers pointing this out -- check the "related" sidebar on the right). Browsers can be configured to send anything at all for any specified file extension, so if you use this value you are in effect blindly trusting user input (bad).

It's better to just extract the extension from the filename and do what you will with that.

Update: I didn't expect to be upvoted too much, but as things stand I feel I should provide some more information.

If you aren't OK with working with just the file extension, you can get the MIME type of a file by using the fileinfo functions as usoban says. Unfortunately, that's only available on PHP 5.3 and up.

A more compatible option is presented as the answer to How to get the content-type of a file in PHP? here on SO (although I find the answer as presented to be a bit of overkill, it's good by any standard).

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Well, mime_content_type() function existed even before PHP5, and provided the same functionality as FileInfo extension, but has been deprecated (a while ago :) – usoban Mar 22 '11 at 16:03
4

Please do not only check for $_FILES['name']['type'], since it's browser who sends this information and it's quite easy to forge the information and for example inject code into file.

To make it more secure, use MIME type checking using FileInfo functions, though, especially with mp3 files, it may be only recognized as application/octet-stream

usoban
  • 5,428
  • 28
  • 42
2

A small selection of MIME types includes:

audio/mpeg: MP3 or other MPEG audio; Defined in RFC 3003
application/pdf: Portable Document Format, PDF has been in use for document exchange on the Internet since 1993; Defined in RFC 3778
sarnold
  • 102,305
  • 22
  • 181
  • 238