File upload in PHP

0

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.

    
asked by anonymous 22.11.2017 / 20:44

1 answer

0

Where it validates UPLOAD_ERR_NO_FILE and then immediately breaks the switch without firing exception is where the error is. Here are my suggestions for changing your code, but note that I've made minor changes to the code just to improve readability. The resolution comes down to just adding the line throw new RuntimeException('No file.'); instead of break .

if (empty($_FILES['file-upload']['name']) === false) {
    try {
        foreach( $_FILES['file-upload']['tmp_name'] as $i => $tempFile ) {
            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:
                    throw new RuntimeException('No file.');
                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);
            $validExtension = 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'
            );

            $ext = array_search($finfo->file($_FILES['file-upload']['tmp_name'][$i]), $validExtension, true);
            if (false === $ext) {
                throw new RuntimeException('Invalid Format!');
            }

            $filnename = sprintf('./uploads/%s.%s', substr(md5(microtime()), rand(0, 26), 10), $ext));
            if (!move_uploaded_file($tempFile, $filename) {
                throw new RuntimeException('Failed!');
            }
        }
    }
    catch (RuntimeException $e) {
        echo $e->getMessage();
    }
}
    
23.11.2017 / 01:48