I'm developing this code to upload files to the server.
But it's not working the way I want it to be:
1 - If the user does not choose any file, it should ignore the file validation (as there is no file);
2 - If there is at least one file, then it should validate all instances $ _FILES, then move to a folder.
HTML:
<form action="insert.php" method="post" enctype="multipart/form-data">
<input id="input-pt-br" name="file-upload[]" type="file" multiple="multiple">
</form>
And PHP validation and upload of files:
if (empty($_FILES['file-upload']['name'])):
else:
for($i = 0; $i < count($_FILES['file-upload']['tmp_name']); $i++){
try {
if (!isset($_FILES['file-upload']['error'][$i]) || is_array($_FILES['file-upload']['error'][$i])
) {
throw new RuntimeException('Invalid parameters.');
}
switch ($_FILES['file-upload']['error'][$i]) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded size.');
default:
throw new RuntimeException('Unknown error!');
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['file-upload']['tmp_name'][$i]),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'webp' => 'image/webp',
'doc' => 'application/msword',
'dot' => 'application/msword',
'xlsx' => 'application/excel',
'xls' => 'application/excel',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pdf' => 'application/pdf',
),
true
)) {
throw new RuntimeException('Invalid Format!');
}
if (!move_uploaded_file(
$_FILES['file-upload']['tmp_name'][$i],
sprintf('./uploads/%s.%s',
substr(md5(microtime()),rand(0,26),10),
$ext
)
)):
throw new RuntimeException('Failed!');
endif;
} catch (RuntimeException $e) {
echo $e->getMessage();
}
}
endif;
You are always entering file validation, even when I am not selecting a file in the input.