You just do a foreach
loop over the $_FILES
array. This is a duplicate of this question and has been asked and answered many times over:
Multiple file upload in php
That being said, since it's been answered already and so I don't just regurgitate what's already out there, I will add a bit more to this answer. In this day and age, you can't just simply upload a file. Likely you will want to keep records of it in a database or show some stats on the view after the page reloads. To do that you need to use a class/method system (in my opinion) where you can actually do the upload but also get useful information back. A framework would take care of all this for you (and more!), but for the sake of this answer, here is a simple example, maybe it will give you ideas:
class Files
{
private $filesArr,
$destination,
$errors,
$success,
$full_path;
/*
** @description This will point the image uploads to a folder
** @param $dir [string] This is the directory where files will save
** @param $make [bool] This will instruct the method to make or not
** make a folder if not exists
*/
public function setDest($dir,$make = true)
{
if(!is_dir($dir)) {
if(!$make || ($make && !mkdir($dir,0755,true)))
throw new Exception('Directory does not exist');
}
$this->destination = $dir;
return $this;
}
/*
** @description This will upload the files and keep some records
** for reference after the fact
*/
public function saveFiles()
{
if(empty($this->filesArr)){
throw new Exception('No files to upload.');
return false;
}
foreach($this->filesArr as $file) {
$filename = $file['name'].'.'.$file['ext'];
if(!move_uploaded_file($file['tmp_name'],$this->destination.'/'.$filename))
throw new Exception('Could not save file "'.htmlspecialchars($filename).'" to folder.');
else {
$this->full_path[] = $this->destination.'/'.$filename;
$this->success[] = $filename;
}
}
}
/*
** @description This organized the files array and allows you to
** set different listeners
*/
public function organize($key)
{
foreach($_FILES[$key]['name'] as $num => $val) {
$ext = $this->getExt($val);
$size = $_FILES[$key]['size'][$num];
$name = pathinfo($val,PATHINFO_FILENAME);
if($_FILES[$key]['error'][$num] != 0) {
$this->errors[] = 'An error occurred: '.htmlspecialchars($name);
continue;
}
elseif(!$this->typeAllowed($ext)) {
$this->errors[] = 'File type not allowed ('.htmlspecialchars($ext).') :'.htmlspecialchars($name);
continue;
}
elseif(!$this->sizeAllowed($size)){
$this->errors[] = 'File too big: '.htmlspecialchars($name);
continue;
}
$this->filesArr[$num]['name'] = $name;
$this->filesArr[$num]['ext'] = $ext;
$this->filesArr[$num]['tmp_name'] = $_FILES[$key]['tmp_name'][$num];
$this->filesArr[$num]['size'] = $size;
$this->filesArr[$num]['tmp_name'] = $_FILES[$key]['tmp_name'][$num];
# I would put a path. I would remove directories outside
# of the root from the destination path. This way you
# can move a website to different web hosts and the
# path will still be good because it will be relative to
# the site root, not the server root. This is only important
# if you plan to store the path in a database...
$this->filesArr[$num]['full_path'] = $this->destination.'/'.$name.'.'.$ext;
}
return $this;
}
/*
** @description This just gives a summary of the actions taken in
** the event
*/
public function getStats()
{
$extsCnt = array();
$fileSum = 0;
if(!empty($this->filesArr)) {
foreach($this->filesArr as $files) {
$store['ext'][] = $files['ext'];
$store['size'][] = $files['size'];
}
if(!empty($store)){
$extsCnt = array_count_values($store['ext']);
$fileSum = array_sum($store['size']);
}
}
return array(
'success'=>(!empty($this->filesArr))? count($this->filesArr):0,
'errors'=>(!empty($this->errors))? count($this->errors):0,
'total_uploaded'=>$fileSum,
'extension_count'=>$extsCnt
);
}
public function toJson()
{
return json_encode($this->getFiles());
}
public function getFiles()
{
return $this->filesArr;
}
public function getErrors()
{
return $this->errors;
}
public function getSuccess()
{
return $this->success;
}
public function getPaths()
{
return $this->full_path;
}
# This method is a little weak. It needs to be more flexible
# Should be able to add/remove file types
public function typeAllowed($ext)
{
return in_array($ext,array("jpeg","jpg","png",'sql'));
}
public function getExt($filename)
{
return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}
public function sizeAllowed($size,$max = 2097152)
{
return ($size <= $max);
}
}
To apply to the page (the business logic) would be something like:
if(isset($_FILES['attach'])){
try {
# Create our instance
$fileManager = new Files();
# Set where we want to save files to
$fileManager
->setDest(__DIR__.'/file/to/save/here')
# Process what name from the form
->organize('attach')
# Do the upload
->saveFiles();
}
# Catch any errors thrown
catch(Exception $e) {
#You would probably want to display this in the view
# so output buffer works here
ob_start();
?>
<script>
alert('<?php echo $e->getMessage(); ?>');
</script>
<?php
$catch = ob_get_contents();
ob_end_clean();
}
}
# Here are some helpful data returns for DB storage or page view
if(isset($fileManager)) {
# Show errors
echo implode('<br />',$fileManager->getErrors()).'<br />';
# Show successful uploads
if(!empty($fileManager->getSuccess()))
echo 'Uploaded: '.implode('<br />Uploaded: ',$fileManager->getSuccess());
# Just some information that can be passed to other classes
print_r($fileManager->getFiles());
print_r($fileManager->getStats());
print_r($fileManager->toJson());
}
# Show alert in the view somewhere
if(isset($catch))
echo $catch;
The return shows something similar to this:
File type not allowed (pdf) : Filename1
Uploaded: Filename2.jpg
Uploaded: Filename3.png
Uploaded: Filename4.png
Array
(
[0] => Array
(
[name] => Filename2
[ext] => jpg
[tmp_name] => /datatmp/phpwDpP27
[size] => 17251
[full_path] => root/path/httpdocs/file/to/save/here/Filename2.jpg
)
[1] => Array
(
[name] => Filename3
[ext] => png
[tmp_name] => /datatmp/phpDXlSmH
[size] => 22636
[full_path] => root/path/httpdocs/file/to/save/here/Filename3.png
)
[2] => Array
(
[name] => Filename3
[ext] => png
[tmp_name] => /datatmp/phpSfE2Hg
[size] => 398811
[full_path] => root/path/httpdocs/file/to/save/here/Filename3.png
)
)
Array
(
[success] => 3
[errors] => 1
[total_uploaded] => 438698
[extension_count] => Array
(
[jpg] => 1
[png] => 2
)
)
[{"name":"Filename2","ext":"jpg","tmp_name":"\/datatmp\/phpwDpP27","size":17251},{"name":"Filename3","ext":"png","tmp_name":"\/datatmp\/phpDXlSmH","size":22636},{"name":"Filename4","ext":"png","tmp_name":"\/datatmp\/phpSfE2Hg","size":398811}]