1

i'm creating a simple file upload mechanism for an asp.net website, and i'm stuck at the validation part, not with the code but with how i should go about checking the files type, considering the uploader needs to only allow certain file types (namely image types) and i feel that validating the extension via regular expression is a bit of a flimsy way of validating the files considering i could upload a pdf with the extension jpg and it wouldn't get flagged.

is using regular expressions the best way of validating a files type?

Edit: asking whether it's best to validate a file type via extension is the best way, not how to do it.

  • What are you going to test against the regular expression? The filename? – CodeCaster Aug 11 '15 at 11:58
  • possible duplicate of [How to validate uploaded file in ASP.NET MVC?](http://stackoverflow.com/questions/6388812/how-to-validate-uploaded-file-in-asp-net-mvc) – CodeCaster Aug 11 '15 at 12:04
  • i'm asking whether validating the file extension is actually the best way of validating the file type, not how to do it. –  Aug 11 '15 at 12:31
  • No, you don't mention extension or filename anywhere in your question, hence my first comment. Anyway no, exactly for the reason you mention: an uploader can easily upload an executable and rename it to `.jpg`. – CodeCaster Aug 11 '15 at 12:33
  • definitely mentioned extension " i feel that validating the extension via regular expression is a bit of a flimsy way of validating the files" –  Aug 11 '15 at 12:34
  • 1
    Wow, I missed that twice. My bad. Guess I fat-fingered that, I did use Ctrl+F... – CodeCaster Aug 11 '15 at 12:35

1 Answers1

1

whether it's best to validate a file type via extension

No. A file extension doesn't say anything.

You don't explain anything about your situation, so I'm going to assume the worst: you're writing a publicly accessible image hosting site where anyone can upload an image and anyone can view images uploaded by anyone.

There have been exploits where a JavaScript file hosted from an HTML <img /> tag would be executed by the browser. So you should open the uploaded file to check whether it actually contains an image.

But it doesn't stop there. Read the (poorly-titled) question Use PHP to check uploaded image file for malware? on http://security.stackexchange.com and read the questions linked to from there to find other potential issues you can run into while building a site where users can upload files. There are many steps you must take if you want to protect your server and your users.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272