PHP image upload security check list
For security test of the image files, I can think of 4 level of securities. They would be:
- Level 1: Check the extension (extension file ends with)
- Level 2: Check the MIME type
($file_info = getimagesize($_FILES['image_file']; $file_mime = $file_info['mime'];)
- Level 3: Read first 100 bytes and check if they have any bytes in the following range: ASCII 0-8, 12-31 (decimal).
- Level 4: Check for magic numbers in the header (first 10-20 bytes of the file). You can find some of the files header bytes from here: http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Examples
Note: Loading entire image would be slow.
Re-process the image using GD (or Imagick) and save the processed image. All others are just fun boring for hackers.
Edit: And as rr pointed out, use move_uploaded_file()
for any upload.
Late Edit: By the way, you'd want to be very restrictive about your upload folder. Those places are one of the dark corners where many exploits happen. This is valid for any type of upload and any programming language/server. Check https://www.owasp.org/index.php/Unrestricted_File_Upload
XSS Warning
One more very important remark. Do not serve/upload anything that could be interpreted as HTML in the browser.
Since the files are on your domain, javascript contained in that HTML document will have access to all your cookies, enabling some sort of XSS attack.
Attack scenario:
The attacker uploads HTML file with JS code that sends all the cookies to his server.
The attacker sends the link to your users via mail, PM, or simply via iframe on his or any other site.
Most secure solution:
Make uploaded content available only on the subdomain or on the another domain. This way cookies are not going to be accessible. This is also one of the google's performance tips:
https://developers.google.com/speed/docs/best-practices/request#ServeFromCookielessDomain