Multiple File Upload Example In PHP

1. Create file first.php

<style>
    input{
        display: block;
    }
    </style>
    <form method="post" action="second.php" enctype="multipart/form-data">
<input type="text" name="user_name">
<input type="password" name="user_password">

Male <input type="radio" name="gender" value="male" checked>
Female <input type="radio" name="gender" value="female">

<input type="checkbox" name="car" value="Maruti"> Car 
<input type="checkbox" name="house" value="Narela"> House 
<input type="checkbox" name="bike" value="Bajaj"> Bike 

<input type="file" name="image[]" multiple>

<input type="submit" value="Click" name="click">
</form>

2. Create file second.php

<?php

$i=0;
foreach($_FILES['image']['name'] as $file => $name)
{
  echo $_FILES['image']["tmp_name"][$file]."<br>";
  echo $_FILES['image']["name"][$file]."<br>";
  echo $_FILES['image']["type"][$file]."<br>";
  echo $_FILES['image']["size"][$file]."<br>";
   
   $ext=pathinfo(basename($_FILES["image"]["name"][$file]), PATHINFO_EXTENSION);

$target_file="./profile".$i.".".$ext;
$i++;
   
   move_uploaded_file($_FILES["image"]["tmp_name"][$file], $target_file);
}

echo "total file ".count($_FILES['image']['name']);
?>

Below code show example for check file size, file extension, file type for uploading valid file

<?php
print_r($_POST);
echo "<br>";
print_r($_FILES);

echo "<br>File Name : ".$_FILES['image']['name']."<br>";
echo "File Type : ".$_FILES['image']['type']."<br>";
echo "File Temp Name  : ".$_FILES['image']['tmp_name']."<br>";
echo "File Size : in bytes ".$_FILES['image']['size']."<br>";
$file=$_FILES['image']['size'] / 1024;
echo "File Size : in KB ".number_format($file, 2)."<br>";
$file=$file / 1024;

echo "File Size : in MB ".number_format($file, 2)."<br>";
echo "File Error : ".$_FILES['image']['error']."<br>";


$ext=pathinfo(basename($_FILES["image"]["name"]), PATHINFO_EXTENSION);
$filename=time();
$target_file="./".$filename.".".$ext;

move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);

?>

Leave a Reply