Search code examples
phpimageimage-uploadingjquery-file-upload

How to verify uploaded image is an actual image and not a harmful code?


For an image uploading website I need to have basic assurity that uploaded file is an image and not a harmful code which could affect server or website clients. Please don't mark this duplicate of any of following questions. I have gone through similar questions.

Need guidance to get started with approaches to do this in practical code implementations in PHP and jQuery front end.

Image sanitization library

Security issues in accepting image uploads

Is it important to verify that the uploaded file is an actual image file?


Solution

  • The first step is to try and determine the image type, which you can do with exif_imagetype, example:

    $valid_types = array('jpeg','jpg','gif','png');
    if (($type = exif_imagetype($_FILES['image']['tmp_name'])) &&
        in_array(ltrim(image_type_to_extension($type), '.'), $valid_types)) {
        // image appears to be valid
    

    For further security, you should upload the file to a folder that is not accessible via the browser, and also rename the image. for example:

    $upload_path = '/path/to/uploads'; // folder ABOVE www or public_html
    $hash = hash_file('sha1', $_FILES['image']['tmp_name']);
    $ext = image_type_to_extension($type);
    $fname = $hash . $ext;
    
    // save it
    if (move_uploaded_file($_FILES['image']['tmp_name'], "$upload_path/$fname")) {
        // image was saved
    

    Or, rather than using move_uploaded_file you could attempt to redraw it with the GD library or Imagick and only save the redrawn copy. It is likely if the image contains any errors then those libraries will fail to draw it.

    That should be secure enough. Even if a user did manage to exploit some vulnerability they would have no way of executing it unless you're feeding it back to them in a predictable way, but it's still very unlikely.