jeudi 5 septembre 2019

File name is never null even without uploading file making condition always true

I have a form that has the option to submit one or more attachments with it, but it is optional. What I have found is when users submit the form without an attachment (file name should be null) that the condition checking if the value is not null: if ($value != null) is always running.

Does anyone see what I am doing wrong?

When I var_dump($_FILES) I get the following array:

array(1) { 
  ["uploadedFile"]=> array(5) { 
     ["name"]=> array(1) { 
       [0]=> string(0) "" 
     } 
     ["type"]=> array(1) { 
       [0]=> string(0) "" 
     } 
     ["tmp_name"]=> array(1) { 
       [0]=> string(0) "" 
     } 
     ["error"]=> array(1) { 
       [0]=> int(4) 
     } 
     ["size"]=> array(1) { 
       [0]=> int(0) 
     } 
   } 
}

Here is the code I have:

foreach ($_FILES as $file) {
    foreach($file['name'] as $key => $value) {
        if ($value != null) { //empty string
            if($file['error'][$key] != 4) { //error code is not #4
                $fu = new fileUpload();
                $filename = $fu->upload();
                $out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). '  uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
                foreach ($filename as $indFile) {
                    $out .= "<li><a href='https://mbkit.com/php/uploads/{$indFile}'>{$indFile}</a></li>";
                }
                $out .= '</ul>';
                $template = str_replace("{filename}", $out, $template);

                echo "name is empty AND error is NOT 4";
            } else { //error code IS #4
                echo "error code is 4";
            }
        } else {
            echo "name is NOT empty!";
        }
    }
}
clearstatcache();

Aucun commentaire:

Enregistrer un commentaire