2 Replies - 505 Views - Last Post: 17 August 2012 - 02:06 PM Rate Topic: -----

#1 BarNunBoi  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 232
  • Joined: 28-March 12

Question: Securest way to check against file type?

Posted 17 August 2012 - 08:23 AM

Hey guys,
I have been doing a little research online as which is the safest, securest way to check the file type of a uploaded file. Some people say they use Mime Content Type, some use $_Files, some even said they use strtolower. What do you guys think is the best solution? I want to write a script that will check the file type of uploaded files and make sure they are XLS documents. Any input will be greatly appreciated! Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: Question: Securest way to check against file type?

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5464
  • View blog
  • Posts: 11,739
  • Joined: 02-June 10

Re: Question: Securest way to check against file type?

Posted 17 August 2012 - 08:50 AM

There are lots of different formats that all end in XLS.
Here is a complete explanation of the Excel document formats:
http://www.openoffic...lfileformat.pdf

The surest way (to me) would be to read the beginning of the file as a byte[] and compare it to the various file format headers to see if it conforms.

But the simpler way might be to try opening the file in Excel. If it fails (throws an exception or error) then it isn't a valid file.
Was This Post Helpful? 0
  • +
  • -

#3 AdaHacker  Icon User is offline

  • Resident Curmudgeon

Reputation: 452
  • View blog
  • Posts: 811
  • Joined: 17-June 08

Re: Question: Securest way to check against file type?

Posted 17 August 2012 - 02:06 PM

View PosttlhIn`toq, on 17 August 2012 - 11:50 AM, said:

The surest way (to me) would be to read the beginning of the file as a byte[] and compare it to the various file format headers to see if it conforms.

Or you could just use the fileinfo extension, which does essentially what you describe. Coincidentally, this is probably also the easiest way to do it too.

But really, it depends on what you're doing with this information. It's a trade-off between accuracy and simplicity - do you really need the check to be absolute 100% accurate all the time, or does it just have to be pretty close? As tlhIn`toq said, the only truly reliable way is to open the file in Excel or some other library that can parse and validate Excel files. However, that has other drawbacks, like requiring you to install Excel on your server. But if all you want to do is stop people from uploading obviously incorrect formats, like if someone tries to upload a pdf rather than an xls, then something like fileinfo will be fine.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1