How to upload Multiple files in PHP

Sharad Jaiswal
Dec 22, 2018 · 2 min read
Image for post
Image for post

When I first started this blog. I showed you how you can upload images to a specified folder using PHP which could only upload one image at a time. This time, I will show you how you can handle multiple image uploads using PHP with a few restrictions. Restrictions are the part which separates image uploading to other files uploading since there’s no totally separate PHP code which can let you upload only image files. Uploading means uploading in PHP and the differences need to be created by you.

Below is your HTML form for uploading-

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

And here’s the PHP code which will let you handle multiple images at a time-

<?php
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $img => $tmp_name ){
$file_name = $_FILES['files']['name'][$img];
$file_size =$_FILES['files']['size'][$img];
$file_tmp =$_FILES['files']['tmp_name'][$img];
$file_type=$_FILES['files']['type'][$img];
//Valid Extensions
$extensions = array("jpeg","jpg","png","JPG");
$file_ext=explode('.',$_FILES['files']['name'][$img]) ;
$file_ext=end($file_ext);
$file_ext=strtolower(end(explode('.',$_FILES['files']['name'][$img])));
//Check For Extension
if(in_array($file_ext,$extensions ) === false){
echo ''.$file_name.' is an Invalid Image Type <br/>';
}
//Error For Large File Size. Max 2MB
else if($file_size > 2097152){
echo ''.$file_name.' Is Too Large To Upload <br/>';
}
else{
//Upload Images to folder named 'gallery'
move_uploaded_file($file_tmp,"gallery/".$file_name);
echo 'Successfully uploaded '.$file_name.'<br/>';
//Do some SQL part here if you want.
}
}
}
?>

Here are the valid extensions which are allowed:

$extensions = array("jpeg","jpg","png","JPG");

And the maximum size for each image must be less than or equal to 2MB which is ‘2097152‘ bits. You can use a greater number if you want. But since you will be using the images on the web, 2MB is already a large file.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store