试图在PHP中上传多个文件

时间:2013-07-24 10:38:04

标签: php file-upload

我一直在努力解决这个问题,希望有人能指出我正确的方向。我有一个脚本,可用于上传单个图像。我现在正在努力使它能够同时更新多个文件。以下示例中的2。我知道名称需要是一个数组,我循环它们然而我似乎只是遇到错误。我已经阅读并尝试了各种不同的东西。

我要么能够上传一个文件而不能上传第二个文件,不上传任何文件或空白屏幕。

以下是我在进行各种编辑后正在使用的内容。

      <?php

    $upload_dir= 'training/trainingDocuments';
    $numUploads = 2;

    $msg = 'Please select files for uploading';
    $errors = array();

    if(isset($_FILES['myTrainingFile']['tmp_name']))
    {
        for($i=0; $i < count($_FILES['myTrainingFile']['tmp_name']);$i++)
        {
            $fileName = $_FILES['myTrainingFile']['name'][$i];
            $tempName = $_FILES['myTrainingFile']['tmp_name'][$i];
            $blacklist = array('exe','php','jsp','js','bat','asp','aspx','com','dmg');
            $a = explode('.', $fileName);
            $fileExt  = strtolower(end($a)); unset($a);
            $fileSize = $_FILES['myTrainingFile']['size'];

            if(in_array($fileExt, $blacklist) === true){
                    $errors[] = "File type not allowed";
            }

            //$newPath = $general->fileNewPath($path, $fileName);

            $newPath = "training/trainingDocuments/" . $_FILES['myTrainingFile']['name'][$i];
            $moveFileResult = move_uploaded_file($tempName, $newPath);
            if($moveFileResult != true){
                $errors[] = 'Upload Failed - MOVE';
            }

            $comments = htmlentities(trim($_POST['comments']));
            $category = htmlentities(trim($_POST['category']));

            //insert into db
            $training->uploadDocument($fileName, $category, $comments);


            if(!is_uploaded_file($_FILES['myTrainingFile']['name'][$i]))
            {
                $errors[] = 'Uploading '.$_FILES['myTrainingFile']['name'][$i] . 'failed -.-';
            }


        }
    }
    ?>

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

尝试使用此代码,我添加了一个名为convert_files的函数,以便您以更好的方式处理上传

<强>代码:

<?php
  $upload_dir = "training/trainingDocuments";
  $numUploads = 2;

  $msg    = "Please select file(s) for uploading";
  $errors = array();

  // how many files you want to upload
  $maxFiles = 3;

  if ( $files = convert_files( $_FILES["myTrainingFile"] ) ) {
    foreach( $files as $i => $file ) {
      $fileName = $file["name"];
      $tempName = $file["tmp_name"];
      $fileSize = $file["size"];
      // get file extension, and do strtolower
      $fileExt  = strtolower( pathinfo( $fileName, PATHINFO_EXTENSION ) );
      // invalid file types
      $blacklist  = array( 'exe','php','jsp','js','bat','asp','aspx','com','dmg' );
      // new path to upload current file
      $newPath  = "training/trainingDocuments/".$fileName;

      // Check whether its a valid file or invalid file
      if ( in_array( $fileExt, $blacklist ) ) {
        // invalid file type, add error
        $errors[$i] = "File type not allowed";
      }

      if ( !is_uploaded_file( $tempName ) ) {
        // its'' not an uploaded file, add error
        $errors[$i] = "Uploading ".$fileName." failed -.-";
      }

      if ( file_exists( $newPath ) ) {
        // file already exists in your directory, add error
        $errors[$i] = "File ".$fileName." already exists";
        // if you dont want to add error, (adding an error will not upload file)
        // just comment above line, and uncomment below line

        /*
        // get the filename without extension
        $name = pathinfo( $fileName, PATHINFO_FILENAME );
        //create new file name
        $fileName = $name."_".uniqid().".".$fileExt;
        //update upload path
        $newPath  = "training/trainingDocuments/".$fileName;
        */
      }

      // make sure $errors[$i] contains any errors
      if ( isset( $errors[$i] ) ) {
        // errors occured, so continue to next file
        continue;
      }

      if ( !move_uploaded_file( $tempName, $newPath ) ) {
        $errors[$i] = "Upload Failed - MOVE"; // failed to move file
      }

      $comments = htmlentities( trim( $_POST['comments'] ) );
      $category = htmlentities( trim( $_POST['category'] ) );

      // Upload document
      $training->uploadDocument( $fileName, $category, $comments );

      // check maximum allowed files limit exceeded
      if ( ( $i + 1 ) == $maxFiles ) {
        // limit exceeded, break the execution
        break;
      }
    }
  }
?>

<强>功能:

<?php
  function convert_files( $files ) {
    if ( is_array( $files ) && !empty( $files["name"] ) ) {
      if ( is_array( $files["name"] ) ) {
        $merged = array();
        foreach( $files["name"] as $i => $name ) {
          $merged[] = array(
            "name"  =>  $name,
            "type"  =>  $files["type"][$i],
            "size"  =>  $files["size"][$i],
            "error" =>  $files["error"][$i],
            "tmp_name"  =>  $files["tmp_name"][$i]
          );
        }
        return $merged;
      }
      return array( $files );
    }
    return false;
  }
?>