0

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?

7
  • 1
    please dont ask someone to write code for you, come up with something own and ask how to go on. nobody will write you an application which does this
    – Alex
    Aug 12, 2014 at 7:20
  • Not asking code, just want right direction. Like effective approaches specific to PHP
    – XIMRX
    Aug 12, 2014 at 7:21
  • > practical code implementations < pretty much seems like code :P but seriously, I'd rather google for this: webcheatsheet.com/php/file_upload.php
    – Alex
    Aug 12, 2014 at 7:23
  • I said guidance to get started with... :P
    – XIMRX
    Aug 12, 2014 at 7:25
  • 2
    Doesn't matter, a valid image could still contain exploit code.
    – l'L'l
    Aug 12, 2014 at 7:42

1 Answer 1

1

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.

2
  • Nice answer mister martin! Can you tell if there are chances that images without any vulnerable content will face error at redrawing step. If it is frequent then I should not use this step. (I mean; do common images have errors frequently that can fail redrawing?)
    – XIMRX
    Aug 12, 2014 at 7:46
  • @XIMRX No, valid images that are not corrupted should never face any errors when redrawing. Aug 12, 2014 at 7:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.