Skip to main content

Command Palette

Search for a command to run...

PHP - Upload of Images With PHP

Security tips for you when uploading images with PHP

Published
2 min readView as Markdown
P

I'm an enthusiastic programmer from Brazil. I know a little bit of PHP, JS, HTML, MySQL. I haven't had time to learn any framework yet, it's something maybe for the future

To upload imagens with PHP it is very easy, but if you don't be carefull will let you system open to hacker.

To upload imagens with PHP or even another type of file you can use the function move_uploaded_file this way:

move_uploaded_file($filename, $destination);

You should never use just the function move_uploaded_file whitout verify the files is not dengerous, in this case for imagens let's see something you need to care about if you don't want to be hacked. I am not saying that is everything you need to concern about, but it was what i could conceive at the moment, if you see another point that we need to be concerd when upload imagens to the server with PHP, please let me know. I want to improve me application security too.

To a More Secure PHP Image Upload

You must....

  1. limit character length of uploaded filename: ex: filename.png
  2. limit file byte size: Ex: 500KB
  3. allow only specific types of mimes: eg ['image/webp','image/jpeg','image/png','image/gif'];
  4. allow only specific extension types: eg ['jpg','png','jpeg']
  5. avoid traversal attack: eg : ../.../etc/file
  6. avoid false extension: ex: foto.png.php
  7. avoid file with weird names: eg %2E%2E%2fetc%2Ffile

Some Remarks About PHP Image Upload

File with weird name like %2E%2E%2fetc%2Ffile have character that can be convert to ../ this would be allowing to traversal attack. This would happen for exemple if you use:

urldecode("%2E%2E%2fetc%2Ffile"); // result ../etc/file

Limiting the size of bytes and the size of the file name may have nothing to do with hackers, but application security does. You probably won't get hacked because the file size is large, but your application may become unstable if you receive multiple requests with huge files.

Files with really big names is something weird, I think some operating systems might even have difficulty dealing with them, I didn't do much testing, but I had created a file with a really big name by Windows CMD and when I tried to delete through the GUI it wasn't possible to delete it, so I managed to delete it by CMD, today I tried again, interesting that it wasn't even possible to create the file, the Windows system was not allowing to create such a large filename. Anyway, remember to limit the size of the filename the user is sending you.

Don't trust the mime type from super global $_FILES