Sunday, July 31, 2022

[FIXED] How to check the content of an uploaded file without relying on its extension?

Issue

How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.

Thanks for any advice.


ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.

In my code I can read the first twenty bytes no problem:

                FileStream fs = File.Open(filePath, FileMode.Open);
                Byte[] b = new byte[20];
                fs.Read(b, 0, 20);

so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?


Solution

Here's a quick-and-dirty response to the followup question you posted:

byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };
bool match = true;
for (int i = 0; i < jpg.Length; i++)
{
    if (jpg[i] != b[i])
    {
        match = false;
        break;
    }
}


Answered By - Jon B
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.