Secure Image Uploading in PHP and theory behind it

Dear All,
After seeing so many questions on how we can do secure uploading of images on the server, I am gonna post a theory of how to do this effectively.
The very first method which is basic uploading:
We just browse an image from our local machine and upload them as following. This method is called a naive method.

This uploading is done through a normal HTML form tag

Unfortunately this has several flaws- 1 – It can easily be guessed that where are you putting your files and so anybody can upload any PHP script or any executable file and get your server down. 2 – Anybody can upload a file which enables shell commands on your machine and can do anything with your server. So this way is never suggested. A simple solution at the first site seems to check for the file type being uploaded. So putting a simple script

Can make your script secure a bit but unfortunately, it also has some flaws.  This PHP method checks content type of the image you are uploading and can be broken by a simple perl script by making header content-type to image/jpg.

Now moving one step ahead let’s check the file type, rather checking content type. There is a function in PHP “getimagesize()” which returns a list with image attribute as below;

This way, we can check for the file type and test whether it’s an image. Now one can ask, are we secure? The unfortunate answer is NO. Even after verifying file type, we are not done? YES, still there is a flaw in this…

A hacker can easily use steganography and embed a PHP code into the image and can break your system(Here my motive is not to teach hacking or steganography. I just want to help others protect their system).  Then? After this, we have one more thing to do with the code and that is; putting your image folder out of your server directory (on Linux /var/www/html directory) or make your uploaded image folder not executable so that even if the hacker uploads malicious image, he shouldn’t be able to run that.

So now are you secure? Ummm… NO! but after these steps, you are highly secure from attacks. In this post, I have tried to cover the security concepts behind image uploading with little coding in php. The code syntax in other languages may or may not be different but the logic would be more or less for all the technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top