First, if you are going to use +=
then you must initialise that variable before you do the first +=
Secondly, you have this line, in the loop, it will be setting the value of $totalFileSize
to Zero, if the value exists and is > 0.
if (!empty($totalFileSize)){
$totalFileSize = 0;
}
So change the code to
$totalFileSize = 0; // init before using `+=`
if (!empty($_FILES['attachment'])) { //If there are attachments
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
for ($i = 0; $i < $count; $i ++) {
//Total File Size
if ($_FILES["attachment"]["size"][$i] != 0){
$totalFileSize += ($_FILES["attachment"]["size"][$i]);
}
}
$message = $totalFileSize;
}
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
This could be simplified to
$totalFileSize = 0; // init before using `+=`
if (!empty($_FILES['attachment'])) { //If there are attachments
foreach( $_FILES['attachment']['size'] as $size){
//add up the File Sizes
$totalFileSize += $size;
}
$message = $totalFileSize;
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
Or even
if (!empty($_FILES['attachment'])) { //If there are attachments
$totalFileSize = array_sum($_FILES['attachment']['size']){
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
Or even
if (!empty($_FILES['attachment'])) { //If there are attachments
if (array_sum($_FILES['attachment']['size']) > 20971520){
$fileSizeError = 1;
}
}