I'm trying to make an image upload form on my website, and I do not know how to ensure that what the user is uploading is a real image.
I could do...
if ($_FILES['imagefile']['type'] == "image/gif" || $_FILES['imagefile']['type'] == "image/jpeg" || etc.)
But that only checks the header. If somebody create a PHP file with a custom header, they could essentially upload the PHP file to my server and use it to kill me, couldn't they?
How do I check whether the file is DEFINITELY an image?
That's an excellent question. That's what I thought to myself when I read this post. This is what I think, and there are probably other, better ways to do this because I am not too well versed in the ways of this file checking stuff (but I can provide a lovely conversation partner).
Why not just check for the file extension? If it's not a valid image (i.e. .png, .gif, .jpg, etc.) then don't allow the upload. People cannot execute scripts that are not parsed so if they do upload a script (php, for example, could be another type) then in order for it to execute then it has to be parsed and as long as you don't have .gif in your .htaccess file as an extension that can be parsed by the php parser, then the script will not be able to execute.
I think you raised a very good concern, but I think it's also being a little over-cautious. Scripts cannot be executed if they cannot be parsed.
Use getimagesize(). This will return false if the file headers are not an image. For an even more thorough check use one of the GD functions (imagecreatefromstring()) for example.
Bookmarks