Looking for how to Upload Multiple Files in PHP? This article is going to give an in-depth tutorial on how to upload Multiple files and Images in PHP.
PHP multiple file uploads give your users an easier task, instead of uploading files one by one.
How to Upload Multiple Files in PHP
To upload multiple files, you will need to take care of the following points:
- HTML input name should be defined as an array i.e.
name = "fileUploads[]";
- Input tag must have an attribute called multiple with a value of multiple i.e.
multiple="multiple"
- In your PHP use the following syntax to get file data:
$_FILES['inputName']['param'][index]
With those 3 points in mind, we can go ahead and start our project.
Please make sure you read how to get file extensions in PHP; we will need this concept while validating the file extension before uploading.
The following code illustrates how to perform multiple-file upload in PHP:
The following code shows the upload process with PHP Script (uploads.php)
// time to upload our files
if(isset($_FILES['uploadFiles']['name'])){
$totalFiles = count($_FILES['uploadFiles']['name']);
$allowedExtensions = array(".png", ".jpg", "jpeg", ".zip", ".gif");
$start = 0;
while($start
$tmp = $_FILES['uploadFiles']['tmp_name'][$start];
$eachFileSize = $_FILES['uploadFiles']['size'][$start];
$eachFileName = $_FILES['uploadFiles']['name'][$start];
// you can check the size of each file
if($eachFileSize > 20000000 ){
// if there is a file greater than 2mbs, then return
echo $eachFileName." is greater than 2mbs. The upload proceess has been terminated";
exit(); // kill the loop
}
$eachFileExtension = strtolower(substr($eachFileName, strlen($eachFileName)-4, strlen($eachFileName)));
// check for illigal file extensions
if(in_array($eachFileExtension, $allowedExtensions)){
// now we can upload
$location = "uploads/".$eachFileName;
move_uploaded_file($tmp, $location);
} else {
// terminate the loop
echo $eachFileName." Contais illigal extension, the upload process has been terminated!";
exit();
}
// check for extensios
// allow images only
echo $eachFileName." has been uploaded to ".$location."
";
$start ++;
}
}