Secure image uploads

I’ve avoided it for ages but I have to implement a system that allows users to upload images to the web server. Can I confirm this is secure?

  1. Files are uploaded to a folder either outside the web root or with Deny from all in the .htaccess
  2. Files are converted to .jpgs and re-saved using GD
  3. Original upload is deleted almost immediately (as soon as conversion above has taken place)
  4. Images are then outputted in the CMS using PHP and .jpg header

Are there any potential problems there? I guess technically step 4 isn’t even needed.


Step 2 could be a problem as normal conversion can still retain code injection within the file. With GD you can read the image into a string and then rebuild it. I can not find the link at the moment but you can search for “jpg code injection” and see what I am talking about.

Thanks, but let’s say you upload a file with injected PHP. How do you execute it given you can’t access the file directly? The file would be read with readfile and outputted using image headers.

P.S. Forgot to say in step 2 I’d resize the image. Would that not get rid of anything malicious?

P.P.S. Am chmod’ing the uploaded file to 0644.

I have tried resizing and it did not help. I would have thought reading a file would be just as bad as displaying it.

There is an interesting article here: and an image with some code injected you can test. The post has been updated since I found it and I will have to check it out again. Open the image before and after your test and see if the code is still there.

You can also add shell codes in a png image as well.

From memory saving a jpg as a png will remove any EXIF data which can also contain bad code.

Perhaps the code could automatically run when the image is loaded? I am not an expert and I would be interested in any test results.

I have tried resizing and it did not help.

I re-saved an image with EXIF data using GD and the EXIF data was gone.

I would have thought reading a file would be just as bad as displaying it.

Why? Provided you don’t read the file in such a way the PHP code will be parsed it should be fine (e.g. fread or readfile would be good choices). I think the only way to read a file and have it execute is if you use include or require as this will parse the PHP. That’d be madness though.

I just spoke to my hosting company and they have it set up so that unless you rename the uploaded file to xxx.php, make it executable and allow it to be directly accessed you’re fine. You’d have to be really, really careless to have an exploit in this way.

I hope this helps someone anyway.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.