I have the following code to check if (resume and reference letter uploaded match desired type (pdf OR doc OR docx) and size (less than 400 kb)
//check file
To do that I usually using something like that:
$filename = $_FILES['field_name']['name']; // Get the name of the file (including file extension).
$ext = strtolower(substr($filename, strpos($filename,'.'), strlen($filename)-1)); //get the extention in lower case
And than check if the file extension is accepted.
Also be aware that that the user can simply change the extension for a dangerous file, so it is safer to check with the mime type
Here is some code I wrote in the past..
function checkFileExtension($ext)
{
if ($ext == 'ai' || $ext == 'pdf' || $ext == 'jpg' || $ext == 'jpeg' || $ext ==
'gif' || $ext == 'eps' || $ext == 'tif' || $ext == 'png' || $ext == 'xls' || $ext ==
'xlsx' || $ext == 'doc' || $ext == 'docx' || $ext == 'ppt' || $ext == 'pptx' ||
$ext == 'zip' || $ext == 'rar' || $ext == 'sitx' || $ext == 'psd' || $ext ==
'indd' || $ext == 'dng') {
$pass = (int)1;
} else {
$pass = (int)0;
}
return (int)$pass;
}
$ext = substr(strrchr($_FILES['file']['name'], "."), 1);
$fileAccepted = checkFileExtension($ext);
$fileSize = $_FILES['file']['size'];
if($fileAccepted==1 && $fileSize > '82428800'){
// do stuff
}
The Mime type for docx
is application/vnd.openxmlformatsofficedocument.wordprocessingml.document
This may be useful:
First check desired mime types to verify:
Microsoft Office MIME Types and List of MIME Types
Then try make your code easier...
$mimeTypes = array('application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation');
if (in_array($_FILES["resume"]["type"], $mimeTypes))
{
// File's OK
}
else
{
// Bad file !
}
Important: User may change file extension, so always check the mime type intead of extension!! =)
The below just uses the mime types to validate a file, then checks the size of both. For a list of most mime types see here or google.
function allowed_file(){
//Add the allowed mime-type files to an 'allowed' array
$allowed = array('application/doc', 'application/pdf', 'another/type');
//Check uploaded file type is in the above array (therefore valid)
if(in_array($_FILES['resume']['type'], $allowed) AND in_array($_FILES['reference']['type'], $allowed)){
//If filetypes allowed types are found, continue to check filesize:
if($_FILES["resume"]["size"] < 400000 AND $_FILES["reference"]["size"] < 400000 ){
//if both files are below given size limit, allow upload
//Begin filemove here....
}
}
}