1

我有一个上传脚本,我喜欢将几张图片上传到一个目录。

我使用这个代码:

$allowed_extension = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$errors = array();
$output = array();

if(!empty($_FILES['image']['tmp_name'])){  

     foreach($_FILES['image']['name'] as $key => $array_value){

        if(!in_array(pathinfo($_FILES['image']['name'][$key], PATHINFO_EXTENSION), $allowed_extension)){
                die("Die!");
        }
    }

    foreach($_FILES['image']['name'] as $key => $array_value){

       $file_name = $_FILES['image']['name'][$key];
       $file_size = $_FILES['image']['size'][$key];
       $file_tmp = $_FILES['image']['tmp_name'][$key];

       $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
       $file_extension = strtolower($file_extension);

         if (!in_array($file_extension, $allowed_extension)){
        $errors[$file_name][] = "format $file_extension in image $file_name is not accepted";
        continue;
         }

         if ($file_size > 2097152){
        $errors[$file_name][] = "maxsize of 2MB on $file_name has reached";
                    }

         if (count($errors) == 0){

        $dir = "a/b/c";

        if (is_dir($dir)){
            mkdir("a/b/c/tmp_images", 0755);
        }else{
            mkdir("a/b/c", 0755);
            mkdir("a/b/c/tmp_images", 0755);
        }

        $path = "a/b/c/tmp_images"; 
        $prifix = basename($file_name, "." . $file_extension);

        //var_dump ($prifix);

        $uploadfile = $path . "/" . $file_name;

        $x = 0;
        while (file_exists($uploadfile)){
               $x ++;
               $uploadfile = "{$path}/{$prifix}-{$x}.{$file_extension}";
            }

            if (move_uploaded_file($file_tmp, $uploadfile)){
               $file_name = basename($uploadfile);
               $output [$file_name] = "OK";

            }else{

            $output[$file_name] = "Failure while Uploading!";
            $errors[$file_name][] = "Failure: Can't move uploaded pictures!";
            }//else...
         }//if(count($errors))...
    }//foreach($_FILES['image']['name']... 
}//if(!empty($_FILES['image']['tmp_name'])... 

问题是那部分:

if(!empty($_FILES['image']['tmp_name'])){  

         foreach($_FILES['image']['name'] as $key => $array_value){

            if(!in_array(pathinfo($_FILES['image']['name'][$key], PATHINFO_EXTENSION), $allowed_extension)){
                    die("Die!");
            }
        }

如果上传两种不同的文件类型,它将取消上传。这是我的第一个问题。在这种情况下,我需要取消上传,因为这是我想在发布表单后构建的文件。因此用户在发布表单后无法进行任何更改。让我们看一下第二部分:

foreach($_FILES['image']['name'] as $key => $array_value){

           $file_name = $_FILES['image']['name'][$key];
           $file_size = $_FILES['image']['size'][$key];
           $file_tmp = $_FILES['image']['tmp_name'][$key];

           $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
           $file_extension = strtolower($file_extension);

             if (!in_array($file_extension, $allowed_extension)){
            $errors[$file_name][] = "format $file_extension in image $file_name is not accepted";
            continue;
             }

             if ($file_size > 2097152){
            $errors[$file_name][] = "maxsize of 2MB on $file_name has reached";
                        ...}

在这里可以看出,实际上应该接近应该显示错误消息。如果我离开第一个 foreach 部分,那么我遇到的问题是,如果有两种不同的文件类型,一个文件将被上传,另一个文件将显示错误消息。

所以应该有一种方法可以将第一个和第二个 foreach 结合起来。如果有人能告诉我正确的方法,我真的很感激。多谢。

更新

好吧,对不起我迟到了。这是我的反馈:在两种不同文件类型的情况下,此代码似乎存在一些问题。这好像是

if (count($errors)>0){
   die ("...")
} 

真的不算。在这种情况下,它将收到错误消息:

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access a/b/c/tmp_images/abc.xls

但它也会对具有允许扩展名的图像进行上传,但这不能成功,因为另一个文件类型错误,我猜。问题是这会导致插入查询被放置在这里:

if (move_uploaded_file($fileTmp, $fileDst)) {
            $output[$fileBase] = "OK";

            **$insert = $db->query("INSERT INTO table ( a, b, c) VALUES('".$a."','".$b."','".$c."')");{

            mkdir("a/b/c/d/e", 0755);
            rename("a/b/c/tmp_images", "a/b/c/d/e/tmp_images");

            $msg ="text abc.";                          

            $to = "xxx@xxx.xx";
            $subject = "xxx ";
            $message = "text";

            $headers  = "From: xxx<xxx@xxx.xx>\r\n";
            $headers .= "Content-type: text/plain; charset=UTF-8\r\n";
            $mailheader .= "Return-Path: failuremail@" .$_SERVER['SERVER_NAME']. "\r\n";
            $mailheader .= "MIME-Version: 1.0\r\n";
            $mailheader .= "Content-Transfer-Encoding: 7bit\r\n";
            $mailheader .= "Message-ID: <" .time(). " noreply@" .$_SERVER['SERVER_NAME']. ">\r\n";
            $mailheader .= "X-Mailer: PHP v" .phpversion(). "\r\n\r\n";

            mail($to, $subject, $message, $headers);

            }//**

            }else{

                $output[$fileBase] = "Fehler beim Upload des Bildmaterials!";
                $errors2[$fileBase][] = "Fehler: Die hochgeladenen Dateien können nicht verschoben werden!";
            }//             
        }//

        if (count($errors) > 0) {
            die("Failurecode: ");
            echo "$errors";
    }...

我想从二维数组中获取错误消息,就像我从其他错误消息中获取它们一样,这些错误消息来自与公式相同的页面上的一维数组。在“死”的情况下,它将打开一个新的空白页面以显示错误。多谢。

4

3 回答 3

1

为此,您将需要两个循环,但您采用的方法略有缺陷。您需要一个对所有文件执行所有验证的验证循环,然后是一个仅将文件移动到永久存储的第二个循环。

像这样的东西(固定):

<?php

  // Settings
  $allowedExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
  $maxSize = 2097152;
  $storageDir = 'a/b/c/tmp_images';

  // Result arrays
  $errors = $output = array();

  if (!empty($_FILES['image'])){  

    // Validation loop (I prefer for loops for this specific task)
    for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {

      $fileName = $_FILES['image']['name'][$i];
      $fileSize = $_FILES['image']['size'][$i];
      $fileErr = $_FILES['image']['error'][$i];
      $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

      // Validate extension
      if (!in_array($fileExt, $allowedExtensions)) {
        $errors[$fileName][] = "Format $fileExt in image $fileName is not accepted";
      }

      // Validate size
      if ($fileSize > $maxSize) {
        $errors[$fileName][] = "$fileName excedes the maximum file size of $maxSize bytes";
      }

      // Check errors
      if ($fileErr) {
        $errors[$fileName][] = "$fileName uploaded with error code $fileErr";
      }

    }

    // Handle validation errors here
    if (count($errors) > 0) {
      die("Errors validating uploads: ".print_r($errors, TRUE));
    }

    // Create the storage directory if it doesn't exist
    if (!is_dir($storageDir)) {
      if (!mkdir($storageDir, 0755, TRUE)) { // Passing TRUE as the third argument creates recursively
        die("Unable to create storage directory $storageDir");
      }
    }

    // File move loop
    for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {

      // Get base info
      $fileBase = basename($_FILES['image']['name'][$i]);
      $fileName = pathinfo($fileBase, PATHINFO_FILENAME);
      $fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
      $fileTmp = $_FILES['image']['tmp_name'][$i];

      // Construct destination path
      $fileDst = $storageDir.'/'.basename($_FILES['image']['name'][$i]);
      for ($j = 0; file_exists($fileDst); $j++) {
        $fileDst = "$storageDir/$fileName-$j.$fileExt";
      }

      // Move the file    
      if (move_uploaded_file($fileTmp, $fileDst)) {
        $output[$fileBase] = "Stored $fileBase OK";
      } else {
        $output[$fileBase] = "Failure while uploading $fileBase!";
        $errors[$fileBase][] = "Failure: Can't move uploaded file $fileBase!";
      }

    }

    // Handle file move errors here
    if (count($errors) > 0) {
      die("Errors moving uploaded files: ".print_r($errors, TRUE));
    }

  }
于 2012-04-12T09:05:29.300 回答
1

试试这个,

$filename = $_FILES["quoteexcel"]["name"]; 
//here $filename is an array of file names to be uploaded
$tmpvalues = $_FILES["quoteexcel"]["tmp_name"]; 
//here $tmpvalues is an array of temporary file names

$j=0;
foreach($filename as $key => $value)
{
 $ext = pathinfo($value, PATHINFO_EXTENSION);       
 if($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='tiff' || $ext=='gif')
 $j = $j;
 else     $j++;                                         
}

if($j==0)
{
 foreach($filename as $key => $value)
  {
     //do the upload process here;
  }
}
else
{
   echo "file format not supported";
}
于 2012-04-12T10:03:53.870 回答
0
if(!empty($_FILES['image']['tmp_name']))
{  
    foreach($_FILES['image']['name'] as $key => $array_value)
    {
        $file_name = $_FILES['image']['name'][$key];
        $file_size = $_FILES['image']['size'][$key];
        $file_tmp = $_FILES['image']['tmp_name'][$key];

        $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
        $file_extension = strtolower($file_extension);          

        if($file_size > 2097152)
        {
            $errors[$file_name][] = "maxsize of 2MB on $file_name has reached";
        }           
        if(!in_array($file_extension, $allowed_extension)
        {
            $errors[$file_name][] = "format $file_extension in image $file_name is not accepted";
        }
    }
}
于 2012-04-12T08:50:11.317 回答