2012-04-19 65 views
-3

我有一個上傳腳本來上傳一些文件到一個目錄。每個文件都會通過循環運行,並且會檢查是否存在大小錯誤或結束錯誤,甚至不會。如果沒有錯誤,它將被上傳。如何從循環中獲取結果的數量

if (is_array($_FILES ['image'] ['tmp_name'])) { 
    foreach ($_FILES ['image'] ['tmp_name'] as $key => $val) { 
     ... 

     if (! in_array ($fileExt, $allowedExtensions)) { 
      $errors [$fileName] [] = "format not accepted"; 
     }... 

      if ((count ($errors1) == 0) && (count ($errors) === 0)) { 
       if (move_uploaded_file ($fileTemp, $fileDst)) { 
       //...        
      } 
     } 
    } 
} 

我的問題是,有沒有一種方法來計算成功通過該循環運行的上傳文件的數量?非常感謝。

+2

基本櫃檯?! – malletjo 2012-04-19 17:09:15

+1

http://stackoverflow.com/questions/4367861/how-can-i-know-a-number-of-uploaded-files-with-php – Seabass 2012-04-19 17:09:20

回答

2

您需要對每次成功上傳進行計數。

象下面這樣:

if (is_array($_FILES ['image'] ['tmp_name'])) { 
    $Counter=0;  // initialize counter variable 
     foreach ($_FILES ['image'] ['tmp_name'] as $key => $val) { 

      $fileName = $_FILES ['image'] ['name'] [$key]; 
      $fileSize = $_FILES ['image'] ['size'] [$key]; 
      $fileTemp = $_FILES ['image'] ['tmp_name'] [$key]; 

      $fileExt = pathinfo ($fileName, PATHINFO_EXTENSION); 
      $fileExt = strtolower ($fileExt); 

      if (empty ($fileName)) 
      continue; 

      if (! in_array ($fileExt, $allowedExtensions)) { 
       $errors [$fileName] [] = "format not accepted"; 
      }... 

       if ((count ($errors1) == 0) && (count ($errors) === 0)) { 
        if (move_uploaded_file ($fileTemp, $fileDst)) { 
        //...   
        $Counter++;  // increment if successful upload 
       } 
      } 
     } 
    } 

echo $Counter; //it will give total count of successfully uploaded files 
+0

這就是我一直在尋找的路上。令人驚訝的是它有多簡單。非常感謝你。 – bonny 2012-04-19 17:48:09

1

只需使用一個計數器變量。我知道您在move_uploaded_file返回true時成功上傳了一個文件,對不對?

$counter = 0; 
//... your code 
if ((count ($errors1) == 0) && (count ($errors) === 0)) { 
    if (move_uploaded_file ($fileTemp, $fileDst)) { 
     $counter++; 
     //... some other code 
    } 
} 

所以,當你離開foreach$counter將有預期值。

相關問題