File uploads are potentially the biggest security risk in Web development. Allowing a third-party to upload files on your server could allow them to delete your files, empty your database, gain user credentials and much more. However, it’s certainly possible to upload files safely, and such functionality can be a great feature of your site.
When allowing users to upload files from their local machine to your server, there are two things that you need to check:
- Mime-type of the uploaded file.
- File extension.
If your script is uploading images, for example, you’ll want to check the mime-type of the uploaded file to make sure they are of the following types: image/png, image/jpeg, image/gif, image/x-png and image/p-jpeg. Once that is done, you need to further check the file extension of the uploaded file. To do this, you should manually assign files an extension based on their mime-type. See sample code below:
$validMimes = array(
‘image/x-png’ => ‘.png’,
‘image/gif’ => ‘.gif’,
‘image/jpeg’ => ‘.jpg’,
‘image/pjpeg’ => ‘.jpg’
$image = $_FILES[‘image’];
die(‘Sorry, but the file type you tried to upload is invalid; only images are allowed.’);
// Get the filename minus the file extension:
$filename = substr($image[‘name’], 0, strrpos($image[‘name’], ‘.’));
// Append the appropriate extension:
$filename .= $validMimes[$image[‘type’]];
// Do something with the uploaded file