Multiple file upload in PHP - rename files

662

I'm a beginner in php and now doing a project in php. I want to upload images(maximum four image files only).I used the following code to upload images.

<script type="text/javascript">
count=1;
function add_file_field()
{
if(count<4)
{
var container=document.getElementById('file_container');
var file_field=document.createElement('input');
file_field.name='images[]';
file_field.type='file';
container.appendChild(file_field);
var br_field=document.createElement('br');
container.appendChild(br_field);
count++;
}
}

</script>



        <div id="file_container">
    <input name="images[]" type="file" id="file[]" />
<br />
    </div> 

        <br><a href="javascript:void(0);" onClick="add_file_field();">Add</a> 

I used the following code for single file upload.It's working

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 100000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "File Error : " . $_FILES["file"]["error"] . "<br />";
}else {
echo "Upload File Name: " . $_FILES["file"]["name"] . "<br />";
echo "File Type: " . $_FILES["file"]["type"] . "<br />";
echo "File Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; 
 echo "File Description:: ".$_POST['description']."<br />";

 if (file_exists("images/".$_FILES["file"]["name"]))
 {
 echo "<b>".$_FILES["file"]["name"] . " already exists. </b>";
 }else
 {

$tmpname=$_FILES["file"]["tmp_name"];
$name=$_FILES["file"]["name"];
$new="jun.jpg";
rename($name,$new);
 move_uploaded_file($_FILES["file"]["tmp_name"],"images/".$new);
  echo "Stored in: " . "images/" .$new."<br />";
 ?>
 Uploaded File:<br>
 <img src="images/<?php echo $new; ?>" alt="Image path Invalid" >
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["file"]["type"]." , file size

I need help to modify this code to upload maximum of 4 images. Can rename function be used to rename a selected file for upload on moving to a specified folder? but it was showing error

Please do help me

408

Answer

Solution:

You should allow multiple file selection in your file input, so you do not have to add a new input over and over again:

<input id="file" type="file" name="images[]" multiple>

After submitting the form you can iterate over$_FILES array like that:

foreach($_FILES['images'] as $file) {
    //your code here --> replace $_FILES['file'] with $file
}

I hope this helps.

639

Answer

Solution:

<?php


if(isset($_POST['submit']))
{

    $count=count($_FILES["images"]["name"]);


for($i=0;$i<$count;$i++)
{   
  if ((($_FILES["images"]["type"][$i] == "image/gif")
 || ($_FILES["images"]["type"][$i]  == "image/jpeg")
|| ($_FILES["images"]["type"][$i]  == "image/pjpeg"))
&& ($_FILES["images"]["size"][$i] < 100000))
{

 if ($_FILES["images"]["error"][$i]  > 0)
 {
 echo "File Error : " . $_FILES["images"]["error"][$i]  . "<br />";
  }
  else 
 {
  echo "Upload File Name: " . $_FILES["images"]["name"][$i]  . "<br />";
 echo "File Type: " . $_FILES["images"]["type"][$i]  . "<br />";
  echo "File Size: " . ($_FILES["images"]["size"][$i]  / 1024) . " Kb<br />"; 

   if (file_exists("public/images/".$_FILES["images"]["name"][$i] ))
  {
   echo "<b>".$_FILES["images"]["name"][$i]  . " already exists. </b>";
   }
   else
  {
    move_uploaded_file($_FILES["images"]["tmp_name"][$i] ,"public/images/".             $_FILES["images"]["name"][$i] );
    echo "Stored in: " . "public/images/" . $_FILES["images"]["name"][$i] ."<br />";
   ?>
   Uploaded File:<br>
   <img src="public/images/<?php echo $_FILES["images"]["name"][$i] ; ?>" alt="Image path    Invalid" >
  <?php
  }
  }
  }else
 {
  echo "Invalid file detail ::<br> file type ::".$_FILES["images"]["type"][$i] ." ,    file    size

image uploaded using for loop..foreach was showing error

621

Answer

Solution:

Here is an example of multi-file upload in PHP

https://github.com/hemantrai88/html5-php_multi-file-upload

68

Answer

Solution:

I have one example which is working, I think this will help you

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" />
    <input type="submit"/>
</form>

In php

if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         mysql_query($query);           
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}

People are also looking for solutions to the problem: javascript - Separating date and month from the given date

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.