Search code examples
phpmysqlmultiple-file-upload

multiple file upload uploads only single post


I have the following code for multiple file uploads using php and mysql. But for some reason , if 'n' files are selected, only the last(or 'n'th) file seems to be uploaded..

Here are the respective files:

HTML

    <form enctype="multipart/form-data" method="post" action="<?php echo htmlentities($_SERVER["PHP_SELF"]);?>">
           <div class="form-group">
           <textarea class="form-control" name="postbox" id="pbox"></textarea>
           </div>
           <h5><strong>Add media:</strong></h5>
           <input type="file" name="pfile[]" multiple="multiple" accept="image/*,audio/*,video/*"><br/>
          <button type="submit" class="btn btn-success" name="psubmit">Post!</button>
          </form>
<div class="posts">
<?php
  if(isset($_POST['postbox'])){
    $ps = escape($_POST['postbox']);
  }
  include_once('includes/uploadfile.php'); ?>
</div>

includes/uploadfile.php

     <?php ob_start();
require_once 'core/init.php';

if(isset($_POST['psubmit']))
    {
        foreach ($_FILES['pfile']['tmp_name'] as $key=>$value)
      {
            $pfname = $_FILES["pfile"]['name'][$key];
            $pftype = $_FILES['pfile']['type'][$key];
            $pfsize = $_FILES['pfile']['size'][$key];
            $pftmploc = $_FILES['pfile']['tmp_name'][$key];
            $pferror = $_FILES['pfile']['error'][$key];
            $blast = explode(".", $pfname);
            $pfextn = end($blast);
            if (!empty($ps) && empty($pfname)) 
            {

                $dbfname = NULL;
                $abc = $get->addPost($a, $ps, $pfname);
                header('location:'.escape($_SERVER['PHP_SELF'])); exit;

            }

            else if (!empty($pfname) && !empty($ps))
            {
                //list($width, $height) = getimagesize($pftmploc);

                 if($pfsize > 20971520) 
                { 
                echo "ERROR: Your file was larger than 20 Megabytes in size.";
                unlink($pftmploc);
                exit();
                } 
                else if(!preg_match("/.(gif|jpg|png|mp3|mp4|avi)$/i", $pfname) ) 
                {
                 echo "ERROR: Restricted file format!Kindly stick to these formats alone:gif,jpg,png,mp3,mp4,avi";
                 unlink($pftmploc);
                 exit();
                }
                 else if($pferror == 1) 
                { // if file upload error key is equal to 1
                echo "ERROR: An error occured while processing the file. Try again.";
                exit();
                }
            }

             $dbfname = rand(100000000000,999999999999).$pfname;
            $updir = "ups/posts/";
            $arraymov = array();
            array_push($arraymov, $dbfname);
            $movrslt = move_uploaded_file($pftmploc,$updir.$dbfname);
            if($movrslt != true)
                {
                    echo 'ERROR: File upload failed. Try again!';
                    exit();
                }
          }  
                $abc = $get->addPost($a, $ps, implode(',',$arraymov));
            header('location:'.escape($_SERVER['PHP_SELF'])); exit;
     }  
?>

File upload function:

public function addPost($user_id,$status,$file_path){
                $query = $this->_db->prepare("INSERT INTO postsinitial (puid, pstatus, postimg) VALUES (:k, :l, :m)");
                $query->bindValue(':k',$user_id);
                $query->bindValue(':l', nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8')));
                $query->bindValue(':m',$file_path);
                $query->execute();
                $rsizes = $query->rowCount();

                 if ($rsizes > 0) {
                  return true;
                  }
                   else
                  {
                   return false;
                  }
            }

I've tried to code to insert each file path as a comma-separated array of values so that a user can upload multiple images for only one record in database.This is important!

Tnx in advance!


Solution

  • Looks like you have got the logic wrong. You have to execute move_uploaded_file() within the same foreach() that loops through the $_FILES array.

    ...
    echo "ERROR: An error occured while processing the file. Try again.";
                exit();
           }
       }
    
       move_uploaded_file(...
    }
    

    What you have done is trying to execute move_uploaded_file() in a separate foreach block using $pftmploc variable as the temporary file path. But since that variable was assigned inside the previous foreach() loop, it represents the last element of the uploaded files array. Thats why you are not getting all the files uploaded.