如果单个文件在多个文件上传中有错误,如何防止任何文件上传

时间:2019-06-03 11:06:07

标签: php

我有一个运行良好的多文件上传脚本,但是如果附件中的任何文件有错误,我想完全阻止任何文件上传。

我使用$ error变量保存错误,并且检查了for()中的每个文件后,我尝试了if($ error == 0){// Upload files},没有错误的文件上传了,我没有想要那个。如果文件有错误,则根本不要上传任何文件。

for ($image=0; $image < $countFiles ; $image++) {
   if($checkFile == false) {
      $error = 1;
      $errorMSG = "— Invalid file attached";
   } else { $error = 0; }

   if(file_exists($FileToUpload)) {
      $error = 1;
      $errorMSG = "— Sorry file exists";
   } else { $error = 0; }

   // NOW AFTER CHECKING FILES AND THERE'S NO ERROR UPLOAD
   if($error == 0) {
      move_uploaded_file();
      // files without errors uploads and ones with error doesn't. I don't want to upload any attached files at all if one or more files has an error.
   }
}

1 个答案:

答案 0 :(得分:0)

好,所以

  1. 从验证循环中删除move_uploaded_file()
  2. 在开始循环之前将$ error设置为0
  3. 一旦发现错误终止循环,就没有意义继续了
  4. 仅当$ error保持为零时,才在验证循环后进行移动。

这是一段伪代码

$error = 0;
for ($image=0; $image < $countFiles ; $image++) {
   if($checkFile == false) {
        $error = 1;
        $errorMSG = "— Invalid file attached";
        break; // stop the loop there is no point continuing
   }

   if(file_exists($FileToUpload)) {
        $error = 1;
        $errorMSG = "— Sorry file exists";
        break; // stop the loop there is no point continuing
   } 
}

// if $error remains at 0, we had no errors so do the move
if ( $error == 0 ) {
    for ($image=0; $image < $countFiles ; $image++) {
        move_uploaded_file();
    }
} else {
    // here you would send the error messages if they exist
}