1

While user uploading a file, is it possible to know if the uploaded file is an image or not,

I am open for any solution, Client Side, Server Side or both and we choose based on the case.

Nosredna
  • 83,000
  • 15
  • 95
  • 122
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301

4 Answers4

6

Yes, by checking the magic number of the file.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
2

May be you can use following code to check if the file is an image.

public bool IsFileAnImage(string filePath)
{
   try
   {
      Image image = Image.FromFile(filePath))
   }
   catch
   {
      return false;   
   }
   finally
   {
      image.Dispose();
   }

   return true;
}
SolutionYogi
  • 31,807
  • 12
  • 70
  • 78
0

This can be done server side with GD by using the function below: ((modified version of this)

function imageFileTypeFromBinary($file)
{

    $binary = file_get_contents($file);

    if (
        !preg_match(
            '/\A(?:(\xff\xd8\xff)|(GIF8[79]a)|(\x89PNG\x0d\x0a)|(BM)|(\x49\x49(\x2a\x00|\x00\x4a))|(FORM.{4}ILBM))/',
            $binary, $hits
        )
    ) {
        return 'application/octet-stream';
            //return false;

    }
    static $type = array (
        1 => '.jpeg',
        2 => '.gif',
        3 => '.png',
        4 => '.x-windows-bmp',
        5 => '.tiff',
        6 => '.x-ilbm',
    );
    return $type[count($hits) - 1];
    // or simply return true
    // return true;
}

should you wish, you can make it return true, or false as opposed to the mime type.

Community
  • 1
  • 1
Jarrod
  • 9,349
  • 5
  • 58
  • 73
-2

A simple way would be to look at the file's extension.

Steven Sudit
  • 19,391
  • 1
  • 51
  • 53
  • 1
    That tells you nothing other than the extension; and is a common way for sites to erroneously allow executables to be uploaded. – NotMe Jul 03 '09 at 18:16
  • 1
    I did say "simple", as opposed to foolproof, but I would suggest that file extension is valuable even if you're concerned that the user would lie. If a user renames virus.exe to funpic.gif, then the extension is making a false promise. However, since it claims to be a gif, we can then test specifically for whether it really is, rejecting it otherwise. Otherwise, we'd have to exhaust all possibilities. – Steven Sudit Jul 03 '09 at 18:21
  • I should probably add that renaming the extension can *make* a dangerous file harmless. For example, a `*.VBS` file that destroys the file system is merely interesting reading when renamed to `*.TXT`. – Steven Sudit Mar 26 '10 at 20:56