Uploading multiple files from two inputs in one form!

Im currently stuck with a bit of coding/not too sure how to do it so its as lightweight as possible. Basically what i’m aiming to do is have a main file form upload, icon upload and a preview upload. I want the main file one to go to one directory and then the other two to go to another!

My current code is this:

(AJAX CODE)

<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
require_once('../system/config-admin.php');
if(!preg_match('/^([1-9][0-9]*|0)(\.[0-9]{2})?$/', $_POST['price']))
{
  echo '<span class="text-danger">You need to put a price</span>';
  die();
}
if(empty($_POST['name']))
{
  echo '<span class="text-danger">Product Name is required!</span>';
  die();
}
if(empty($_POST['sdesc']))
{
  echo '<span class="text-danger">Short Description is required.</span>';
  die();
}
if(empty($_POST['description']))
{
  echo '<span class="text-danger">Description is required.</span>';
  die();
}
if(empty($_POST['cat_id']))
{
  echo '<span class="text-danger">Category is required.</span>';
  die();
}
if($_FILES['mainfile']['size'] < 1)
{
echo 'The main file needs to br uploaded and must be .zip';
die();
}
if($_FILES['iconimgfile']['size'] < 1)
{
echo 'The iconimgfile file needs to br uploaded';
die();
}
if($_FILES['previewimgfile']['size'] < 1)
{
echo 'The previewimgfile file needs to br uploaded';
die();
}/*
if($_FILES['file']['size'] < 1)
{
echo 'You need to upload a file! Please try again!';
die();
}*/


$name2 = $_POST['name'];
$sdesc = $_POST['sdesc'];
$description = $_POST['description'];
$cat_id = $_POST['cat_id'];
$demo = $_POST['demo'];
$price = $_POST['price'];
$date = date("Y-m-d");
$featured = (isset($_POST['featured'])) ? 1 : 0;
$support = (isset($_POST['support'])) ? 1 : 0;

$preview_img = $_FILES['previewimgfile'];
$icon_img = $_FILES['iconimgfile'];
$mainfile = $_FILES['mainfile']; 

if(isset($_FILES['mainfile'])){
  $name = $_FILES['mainfile']['name'];
  $name = preg_replace("/[^a-zA-Z0-9áéíóúüñÁÉÍÓÚÜÑ.\']/", "", $name);
  $tmp_name   = $_FILES['mainfile']['tmp_name'];
  $file_size = $_FILES['mainfile']['size'];
  if($file_size < 1)
  {
    echo '<span class="text-danger">No file selected.</span>';
    die();
  }
  $file_type = pathinfo($name);
  $file_type = $file_type['extension'];
  $allowed_file = array('zip,jpg,png');
  if(!in_array($file_type, $allowed_file)){
    echo '<span class="text-danger">Please select a .zip file for the main file & jpg/png for icon img and preview img!</span>';
  }
  else
  {
    $new_file_name = time().$name;
    if(move_uploaded_file(''.$tmp_name.'', '../system/assets/uploads/product-files/'.$new_file_name.''))
    {
      $sql_upload = "INSERT INTO dsptesty_products (name, short_des, description, cat_id, icon_img, preview_img, file, price, demo, created, support, featured, active) VALUES ('$name2', '$sdesc', '$description', '$cat_id', '$icon_img', '$preview_img', '$new_file_name', '$price', '$demo', '$date', '$support', '$featured', '1')";
      if($DB_con->query($sql_upload) === TRUE)
      {
        echo '<span class="text-success">Product added for selling.</span>';
      }
    }
  }
}
else {
  echo '<span class="text-danger"> No files selected.</span>';
}
}
else {
  header('location: ../index.php');
}
?>

(FORM CODE)

       <form id="upload" class="form-horizontal">
             <div class="form-group"> <label>Name:</label> <input class="form-control" name="name" id="coupon-code" type="text"></div>
             <div class="form-group"> <label>Short Description:</label> <input class="form-control" name="sdesc" id="coupon-code" type="text"></div>
            <div class="form-group"> <label>Description:</label> <textarea type="text" class="form-control" name="description" id="coupon-code"></textarea></div><hr>
             <div class="form-group"> <label>Category:</label> <div class="input-group mb-3">
  <select class="custom-select" name="cat_id" id="inputGroupSelect01" required>
    <option value="">Select Category...</option>
    <?php foreach($category as $cat) {
?>
    <option value="<?php echo $cat['id']; ?>"><?php echo $cat['name']; ?></option>
    <?php } ?>
  </select>
</div></div>
              <div class="form-group"> <label>Item Price:</label> <div class="input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text">$</span>
  </div>
  <input type="number" name="price" class="form-control" aria-label="Amount">
  <div class="input-group-append">
    <span class="input-group-text">.00</span>
  </div>
</div></div>
               <div class="form-group"> <label>Live Preview:</label> <input class="form-control" name="demo" id="coupon-code" type="url"></div><hr>
       
         <div class="form-check">
    <input type="checkbox" name="featured" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Featured Item</label>
  </div>
    <div class="form-check">
    <input type="checkbox" name="support" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Support item</label>
  </div>
       
       <hr>
                    <div class="form-group"> <label>Main File (.ZIP):</label> 
                                   <div class="input-group">
  <div class="custom-file">
    <input type="file" name="mainfile" class="custom-file-input" id="inputGroupFile04">
    <label class="custom-file-label" for="inputGroupFile04">Choose File</label>
  </div>
</div>
                    </div>

                    <div class="form-group"> <label>Icon Image File (.PNG,.JPG):</label> 
                                   <div class="input-group">
  <div class="custom-file">
    <input type="file" name="iconimgfile" class="custom-file-input" id="inputGroupFile04">
    <label class="custom-file-label" for="inputGroupFile04">Choose File</label>
  </div>
</div>
                    </div>
                    
                                        <div class="form-group"> <label>Preview Image File (.PNG,.JPG):</label> 
                                   <div class="input-group">
  <div class="custom-file">
    <input type="file" name="previewimgfile" class="custom-file-input" id="inputGroupFile04">
    <label class="custom-file-label" for="inputGroupFile04">Choose File</label>
  </div>
</div>
                    </div>

<hr>
<button type="submit" id="btn" class="btn btn-primary w-100">Upload</button>
<script type="text/javascript">
  $("#upload").on("submit",(function(e) {
    e.preventDefault();
    $.ajax({
          url: "<?php echo $setting['website_url'];?>/admin/ajax-upload.php",
      type: "POST",
      data:  new FormData(this),
      contentType: false,
          cache: false,
      processData:false,
      beforeSend: function() 
        {
            $("#res").html('Uploading..Please wait!');
        },  
        success: function(response)
        {
            $("#res").html(response);
        }        
     });
  }));
</script>
<div id="res"></div>
</form> 

but basically im not too sure how to do multiple files from 3 inputs but currently the main file bit works fine but im trying to make the images part work but i dont know how to do it without writing pointless code etc

All help appreciated

This is a logical error as $allowed_file is just an array with one string entry, and not the array you expect, and for that in_array will not behave the way you want it to.

Also i only see a single move_uploaded_file even that you said you want to upload multiple files.

Here is a small template that may help to get your code cleaner

<?php

class ImageUploader {
    private $pdo = null;
    private $allowed = ['image/jpeg', 'image/png']; // look for MIME-types
    private $path = '/path/to/main-images'; // destination path
    
    public function __construct($pdo){ // hold database connection
        $this->pdo = $pdo;
    }
    
    public function upload($file){
        // check for size etc.
        // generate unique name
        // move uploaded file
        // process SQL - USE PREPARED STATEMENTS HERE, USERS SHOULD NOT DELETE YOUR DATABASE
    }
}

class IconImageUploader extends ImageUploader {
    private $path = '/path/to/icon-images'; // overwrite destination path
}

class PreviewImageUploader extends ImageUploader {
    private $path = '/path/to/preview-images';
}

$mainimage = new ImageUploader($dbcon);
$mainimage->upload($_FILES['mainfile']);
1 Like

Thankyou thats a great method!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.