My site allows users to upload their images. I want to make sure that this is a safe way to do it, it may not be THE safest but I would like to know if it's safe.
Thanks for looking:

if ($_FILES['imageupload']['type'] == "image/gif" OR $_FILES['imageupload']['type'] == "image/pjpeg" OR $_FILES['imageupload']['type'] == "image/jpeg" AND $_FILES['imageupload']['size']<$max_file_size )

    If you're just making sure to limit what type of file they upload, yes, it's safe. However, you could do it easier:

    $allowed = array('pjpeg'=>'image/pjpeg', 'jpeg'=>'image/jpeg', 'jpg'=>'image/jpeg', 'gif'=>'image/gif');
    
    if(in_array($_FILES['imageupload']['type'], $allowed))
    {
        // Seems to be an OK extension, and an OK mime type.
    }

    But that just checks mime types. You might also want to check extensions (which is an easy addition) in where you'd see if [man]array_key_exists[/man] for that file. If it doesn't exist, then you can't upload, if it does, then you can.

      You probably want to check that the mime type, extension and the true type of the file are all in agreement, and the file is a valid image.

      Telling if a file is a valid image isn't terribly straightforward, particularly if the image is too big to fit in memory.

      You can of course use getimagesize() to tell you the dimensions and format, but it won't tell you if the file is completely well-formed. For that, you need to load it in entirely, with e.g. imagecreatefrom* functions.

      These will generally give a E_WARNING if there is something wrong with the image, and/or may fail to load the image entirely. You can catch this and behave accordingly.

      Some malware comes in the form of a malformed image which breaks the web browser and subverts it into doing something malicious.

      One way of defending against this is loading the file into a temporary file on your server and having an on-access virus scanner installed - which will hopefully immediately scan the file before PHP is allowed to read it again, and return an error code (e.g. access denied) if it's found to contain a virus. Consult your server AV software developer documentation for more details.

      Mark

        Write a Reply...