views:

124

answers:

2

The title says it all. If a file is uploaded to the server, how can I make sure that it's actually a picture (not just a file with a .jpg or .gif extension)?

+6  A: 

Using the GD library.

PHP: GD - Manual

array getimagesize ( string $filename [, array &$imageinfo ] )

The first element of the array will be 0 if there is no image. PHP: getimagesize

If you don't have GD installed (most of the time you will), you can read the file header as Shane mentioned.

snicker
+1  A: 

The most efficient way would be to look at the beginning bytes of the file and test for 'magic number' file specifier. Here is a list of magic numbers.

Shane C. Mason
That would be the more efficient than firing up GD, but I think with the binary opens, etc.. is a bit over the head of most people.
Daren Schwenke
If that's true - its pretty disappointing. Don't most of the people here have CS degrees?
Shane C. Mason
I don't.. but I've been writing code since I was 7. Surprisingly, many people can get degrees without actually knowing what they're supposed to. I speak from experience, because I do actually have a degree in civil engineering, and I knew a lot of "sliders" that just slid by. A degree doesn't mean anything. Proof that you can do something does.
snicker
Oh and I believe that a large number of the users of this site do not have CS degrees. Most people end up here from Google who are trying to learn something about the language they are learning.
snicker
Agreed - I saw that for myself. However - it is still disappointing to think of people with programming jobs (as I assume many of these do) and that binary opens are over their head.
Shane C. Mason