Ayan Ayan - 3 months ago 16
jQuery Question

Improve file extension detection and restriction on upload

I know there are many questions and answers related to this but I would like to know the best way to do the restriction on file extension on both server and client side.

PHP

$allowedTypes = array('gif', 'png', 'jpeg', 'jpg', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'mp3', 'mp4', 'rar', 'zip', 'txt');

$File_Name = strtolower($_FILES['uploadfile']['name']);
$File_Ext = pathinfo($File_Name, PATHINFO_EXTENSION);
if(!in_array($File_Ext, $allowedTypes)) {
die('Unsupported File format!');
}


JS

var ftype = $('#uploadfile')[0].files[0].type; // get file type

//allowed file types
switch(ftype)
{
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
case 'text/plain':
case 'text/html':
case 'application/x-zip-compressed':
case 'application/x-rar-compressed':
case 'application/octet-stream':
case 'application/pdf':
case 'application/msword':
case 'application/vnd.ms-excel':
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
case 'video/mp4':
break;
default:
notify("Unsupported file type!");
return false
}

Answer

You can use accept attribute at <input type="file"> element

accept

If the value of the type attribute is file, this attribute indicates the types of files that the server accepts; otherwise it is ignored. The value must be a comma-separated list of unique content type specifiers:

  • A file extension starting with the STOP character (U+002E). (E.g.: ".jpg,.png,.doc")

<input type="file" accept=".gif,.png,.jpeg,.jpg,.pdf,.xls,.xlsx,.doc,.docx,.ppt,.pptx,.mp3,.mp4,.rar,.zip,.txt" />