views:

43

answers:

3

when you upload files, you can then get the necessary data from $_FILES files contains the list of file inputs, where each one has a field like [type]

for example:

Array
(
    [file1] => Array
        (
            [name] => 'MyFile.txt'
            [type] => text/plain  //where does this come from?
            [tmp_name] => /tmp/php/php1h4j1o
            [error] => UPLOAD_ERR_OK
            [size] => 123
        )
)

does it come from within the file, or the file extension, or somewhere else? how does php get the type? where does the [type] come from and can I trust it as valid?

+5  A: 

from the manual:

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

seengee
+3  A: 

The browser attempts to determine the MIME type from the file name, possibly from its extension, then sends this as part of the upload request. Thus, in your example, the file extension .txt would correspond to a MIME type of text/plain. This depends on the browser's implementation though.

Since not only does every browser have its own way of determining the MIME type, but the MIME type can also be intentionally spoofed simply by changing the file extension (among a plethora of other methods), it should not be trusted as always correct.

In fact, you're much better off trying to read the contents of the file or something to validate it.

BoltClock
Is the downvoter not going to speak up?
BoltClock
evidently the downvoter likes me!
seengee
@seengee: -clicks everyone's answer scores- Yeah, somehow! :O
BoltClock
@BoltClock I know this looks highly suspect on my behalf but honestly wasnt me!
seengee
@seengee: Don't worry, I trust you! Your reputation wouldn't still be ending in 5 if you were casting downvotes here ;)
BoltClock
@seengee - only to SO newcomers, others realize you couldn't have upvoted your own answer :)
Nick Craver
@Nick Craver who says he couldn't :P (as someone else)
YuriKolovsky
+1  A: 

The type is determined and set by the browser. That means it'll be influenced by browser make, version, installed programs and a plethora of other things. In other words, it's pretty much useless to the server-side application.

(For example, this means that photos uploaded by MSIE will have type => image/pjpeg; while the most common MIME type for JPEGs is image/jpeg)

Piskvor
AFAIK it's used for progressive (hence the P) JPEGs.
Matteo Italia
yeah, used for progressive jpegs and only sent for them
seengee
@Matteo Italia: Interesting, didn't know that.
Piskvor