null
null

Reputation: 3517

Trying to upload multiple files in PHP

I've been struggling with this for a while now and hoping someone can point me in the right direction. I have a script that works for uploading a single image. I'm now trying to amed it so that I can update more than 1 file at once. 2 in the example below. I understand that name needs to be an array and I loop through them however I only seem to be encountering errors. I've read and tried various different things.

I either was able to upload one file but not the second, upload no files or a blank white screen.

Below is what I'm currently working with after having various edits.

      <?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 -.-';
            }


        }
    }
    ?>

Thanks for any help!

Upvotes: 2

Views: 290

Answers (1)

bystwn22
bystwn22

Reputation: 1794

Try this code, i added a function named convert_files, so you can handle your uploads in a better way

Code:

<?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;
      }
    }
  }
?>

Function:

<?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;
  }
?>

Upvotes: 2

Related Questions