How do I tell if someone's faking a filetype?

2020-06-03 01:33发布

I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later. When users upload files to my server, PHP tells me what filetype it is based on the extension. However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keeping a zip file on my server. Is there any reasonable way to open an uploaded file and "check" to see if it truly is of the said filetype?

9条回答
仙女界的扛把子
2楼-- · 2020-06-03 01:40

Magic number. If you can read first few bytes of a binary file you can know what kind of file it is.

查看更多
Fickle 薄情
3楼-- · 2020-06-03 01:42

Many filetypes have "magic numbers" at the beginning of the file to identify them, You can read some bytes from the front of the file and compare them to a list of known magic numbers.

查看更多
forever°为你锁心
4楼-- · 2020-06-03 01:42

For an exact answer on how you could quickly do this in PHP, check out this question: How do I find the mime-type of a file with php?

查看更多
5楼-- · 2020-06-03 01:46

Check out the FileInfo PECL extension for PHP, which can do the MIME magic lookups for you.

查看更多
太酷不给撩
6楼-- · 2020-06-03 01:49

As a side note I ran into a similar problem where I had to do my own type checking. The front end interface to my application was done in flash. The files were being passed through flash to a php script. When I was attempting to do a MIME type check using php the type always returned was application/octetstream because it was coming from flash.

I had to implement a magic numbers type paradigm. I simply created an xml file that held the file type along with some defining patterns found within the beginning of the file. Once the file reached the server I did some pattern matching with the xml file and then accepted or rejected the file. I didn't noticed any real performance decrease either which I was expecting.

This is just a side note to anyone who may be using flash as there front end and trying to type check the file once it is uploaded.

查看更多
趁早两清
7楼-- · 2020-06-03 01:52

On a unix system, capturing the output from the 'file' command should provide adequate info.

查看更多
登录 后发表回答