php[tek] 2018 : Call for Speakers

Uploading multiple files

Multiple files can be uploaded using different name for input.

It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes:

Example #1 Uploading multiple files

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized (as well as in $HTTP_POST_FILES for PHP versions prior to 4.1.0). When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.

Warning

Since PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.

add a note add a note

User Contributed Notes 15 notes

up
212
phpuser at gmail dot com
12 years ago
When uploading multiple files, the $_FILES variable is created in the form:

Array
(
    [name] => Array
        (
            [0] => foo.txt
            [1] => bar.txt
        )

    [type] => Array
        (
            [0] => text/plain
            [1] => text/plain
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpYzdqkD
            [1] => /tmp/phpeEwEWG
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 123
            [1] => 456
        )
)

I found it made for a little cleaner code if I had the uploaded files array in the form

Array
(
    [0] => Array
        (
            [name] => foo.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpYzdqkD
            [error] => 0
            [size] => 123
        )

    [1] => Array
        (
            [name] => bar.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpeEwEWG
            [error] => 0
            [size] => 456
        )
)

I wrote a quick function that would convert the $_FILES array to the cleaner (IMHO) array.

<?php

function reArrayFiles(&$file_post) {

   
$file_ary = array();
   
$file_count = count($file_post['name']);
   
$file_keys = array_keys($file_post);

    for (
$i=0; $i<$file_count; $i++) {
        foreach (
$file_keys as $key) {
           
$file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return
$file_ary;
}

?>

Now I can do the following:

<?php

if ($_FILES['upload']) {
   
$file_ary = reArrayFiles($_FILES['ufile']);

    foreach (
$file_ary as $file) {
        print
'File Name: ' . $file['name'];
        print
'File Type: ' . $file['type'];
        print
'File Size: ' . $file['size'];
    }
}

?>
up
41
wizzard351 at yahoo dot com
3 years ago
This is also needed for <input type=file multiple> elements.

So, if you have an input element like this:
<input type="file" multiple="multiple" name="foobar" />
This should be written as
<input type="file" multiple="multiple" name="foobar[]" />
else you'll only be able to get one of the files.
up
14
timspeelman at live dot nl
6 years ago
The cleanest way to rearrange the $_FILES

<?php
function rearrange( $arr ){
    foreach(
$arr as $key => $all ){
        foreach(
$all as $i => $val ){
           
$new[$i][$key] = $val;   
        }   
    }
    return
$new;
}
?>
up
4
lookphp at gmail dot com
1 year ago
This is a very simple example:

Part I : HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="upload.php" method="post" multipart="" enctype="multipart/form-data">
        <input type="file" name="img[]" multiple>
        <input type="submit">
    </form>
</body>
</html>

Part II : PHP

<?php
echo '<pre>';
$img = $_FILES['img'];

if(!empty(
$img))
{
   
$img_desc = reArrayFiles($img);
   
print_r($img_desc);
   
    foreach(
$img_desc as $val)
    {
       
$newname = date('YmdHis',time()).mt_rand().'.jpg';
       
move_uploaded_file($val['tmp_name'],'./uploads/'.$newname);
    }
}

function
reArrayFiles($file)
{
   
$file_ary = array();
   
$file_count = count($file['name']);
   
$file_key = array_keys($file);
   
    for(
$i=0;$i<$file_count;$i++)
    {
        foreach(
$file_key as $val)
        {
           
$file_ary[$i][$val] = $file[$val][$i];
        }
    }
    return
$file_ary;
}
up
7
Corey Ballou
7 years ago
Here is a function to fix the indices of a multi-dimensional for easier parsing when dealing with file uploads.  It takes a single $_FILES field array as a parameter and separates each individual uploaded file by numeric key.  This allows for iterating like:

<?php
fixFilesArray
($_FILES['array_of_files']);
foreach (
$_FILES['array_of_files'] as $position => $file) {
   
// should output array with indices name, type, tmp_name, error, size
   
var_dump($file);
}
?>

Here's the code:

<?php
/**
* Fixes the odd indexing of multiple file uploads from the format:
*
* $_FILES['field']['key']['index']
*
* To the more standard and appropriate:
*
* $_FILES['field']['index']['key']
*
* @param array $files
* @author Corey Ballou
* @link http://www.jqueryin.com
*/
function fixFilesArray(&$files)
{
   
$names = array( 'name' => 1, 'n cla => 1, 'n'tmp_nam => 1, 'n'tmr, sispan>=> 1, 'n'tm'=> 1,
    foreach (
$file_aryspan>as $key=> $file/foran>) {
    // shou be aing h indi/spid         $newn= 'n)pan>$key) {< />        }$files [$val] = <) ;$keyis_a($_FIL/foran>) {            $file/forpan>as $key=> $filee ) {
    $file_arysan>[$val][$i] = $val) {< />        <i;   }
    retup;   // shoute.ovd ild <>    retup;   ) {$file_arysan>[$val] = <) />        }
    }
&nbs />
?>
up
down
212
CorejContat semlabs com HereIu haveto uapprad more_arysp multiple ensional for s </><input type="file" mult="img[ission syn[screonahot>
elseinput type="file" mult="img[r.php[dem][][img]/>
else/>elsewill needone lasunexpd">Enmat:</><n class="default"><?php
as     'n'tm'ssion synppan>=>         (
            [naman>'name' => 'namescreonahotppan>=> 'namemon_globw" ipaper'){            [naman>'namea => 'namescreonahotppan>=> 'namees/no/jpesppan>){            [naman>'namea_nam => 'namescreonahotppan>=> 'name/phpeEwE48lX2Yppan>){            [naman>'namer, sispan>=> 'namescreonahotppan>=> 0){            [naman>'name'=> 'namescreonahotppan>=> 0){        &nbsr,/>&nbs> ./>?>
Herewilldo tthe sameowing: *<?php
function reareas($file_arysan>[$files = arranulpan>][$filenewpan>= arrafalsaan>) {$filepaultan>= arrafalsapan>){
   
$names = array( 'name' => 'name']);'n cla => 'type'];'n'tmp_nam => 'tmp_name'],'n'tmr, sispan>=> 'n'tmr, sisan>, 'n'tm'=> 'n'tm'=>r />   
    foreach($file_aryspan>as $key=> $file/forpan>as < />    {
       
$newn= 'n )pan>$key) {< />        }$filin_a($file/span>) {$files as <) />        {$names = arra) {< />        }$filin_a($file/span>) {$files as <) />        {$filepaulan>[$val) {< />        }$filis_a($file/forpan>as < />        {$filepaorpan>as arrafas($file/foran>) {$files ) {$filesspan>;$filepaultan>=         }
$filis_a($file/forpan>as < />        {
           
$filecur pan>=> $key;
}$filepaultan>= $keyas < />    {$filecur pan>=> $key[$key[        }$filecur an>[$key) {<$val) {< />        }$filepaultan>=         }$names = arranulpan>][        }
    }
    retu/>    return
$file/span>;
}
?>
down
212 0
Coreswayalexgmail dot com HereRecursive solu
I wrtion                             <i;   }
            <i;   }
    retup;       retup;       }

    foree_aryspray();
        <>    retup;               retup;                                           <i;   }
        }
    }
&nbs/>    return }
down
14 -3
Corehot dot[at]s-vultix> When multiple file uploads fro/>&nbs/>&nbs" mu_max_s '
I wrads fr_max_s, th ' < ads fr_max_s, th ' 2M/>
I wryilldo tseppr12e_aryspof upfix 2 MB apprthe upfix 1 MB a liyillitddn
So, As lclasyspyillh (du be angle $_FIcopypof 1g uploinix memorye $_FImemory_limit directiveldo tbe harrah (s/soto gsmonlyyspwellpan>
down
212 -
CorejefBallno >
WhenOncead the ue coultiainichor"loinulthuge ERPt woulthe severor iple filead moret typ onesid inpuy.
</><inpueas nput type="file" multiple="mut="img[ad mor[av>r>
elseinput type="file" multiple="mut="img[ad mor[att(//>
elseinput type="file" multiple="mut="img[ad mor2[av>r>
elseinput type="file" multiple="mut="img[ad mor2[att(//>
elseinput type="fileit">t;
elseinpum>
</><T_FILES array to tis ch (urra this:
</><y
(
    [0] =ad morgt; Array
        (
            [name] => bar.y
        (            [namp;       [nameav>r&t; text/pmur.c/>            [namp;       [nameatt(//&t; text/pmur/>            [namp;   &nbs />
    [1] p;       [name] => texty
        (            [namp;       [nameav>r&t; text/pxt/x-csrc/>            [namp;       [nameatt(//&t; textapplicn set/octet-ng>eam/>            [namp;   &nbs />
    [1] p;       [name]ame] => /tmpy
        (            [namp;       [nameav>r&t; text/opt/lvotp/tehpeEwEuf3KNj/>            [namp;       [nameatt(//&t; text/opt/lvotp/tehpeEwE0yPZap/>            [namp;   &nbs />
    [1] p;       [namer, sigt; /tmpy
        (            [namp;       [nameav>r&t; text0/>            [namp;       [nameatt(//&t; text0/>            [namp;   &nbs />
    [1] p;       [nameh ' gt; /tmpy
        (            [namp;       [nameav>r&t; text3"60/>            [namp;       [nameatt(//&t; text8661/>            [namp;   &nbs />
    [1] p;   &nbs />
    [1] =ad mor2gt; Array
        (
            [name] => bar.y
        (            [namp;       [nameav>r&t; textjefBal."> W/>            [namp;       [nameatt(//&t; texts-vas.txt/>            [namp;   &nbs />
    [1] p;       [name] => texty
        (            [namp;       [nameav>r&t; text/pxt/"> W/>            [namp;       [nameatt(//&t; text/pxt/plain/>            [namp;   &nbs />
    [1] p;       [name]ame] => /tmpy
        (            [namp;       [nameav>r&t; text/opt/lvotp/tehpeEwE87nfyu/>            [namp;       [nameatt(//&t; text/opt/lvotp/tehpeEwEUBlvVz/>            [namp;   &nbs />
    [1] p;       [namer, sigt; /tmpy
        (            [namp;       [nameav>r&t; text0/>            [namp;       [nameatt(//&t; text0/>            [namp;   &nbs />
    [1] p;       [nameh ' gt; /tmpy
        (            [namp;       [nameav>r&t; text583/>            [namp;       [nameatt(//&t; text191/>            [namp;   &nbs />
    [1] p;   &nbs />
&nbs />
&nbsI'vrmmanagedfix re-nge the $_llow to t this:
</><y
(
    [0] =ad morgt; Array
        (
            [nameav>r&t; texty
        (            [namp;       [name] => /tmp/pmur.c/>            [namp;       [name] => text/pxt/x-csrc/>            [namp;       [name]ame] => /tmp/opt/lvotp/tehpeEwEuf3KNj/>            [namp;       [namer, sigt; /tmp0/>            [namp;       [nameh ' gt; /tmp3"60/>            [namp;   &nbs />
    [1] p;       [nameatt(//&t; texty
        (            [namp;       [name] => /tmp/pmur/>            [namp;       [name] => textapplicn set/octet-ng>eam/>            [namp;       [name]ame] => /tmp/opt/lvotp/tehpeEwE0yPZap/>            [namp;       [namer, sigt; /tmp0/>            [namp;       [nameh ' gt; /tmp8661/>            [namp;   &nbs />
    [1] p;   &nbs />
    [1] =ad mor2gt; Array
        (
            [nameav>r&t; texty
        (            [namp;       [name] => /tmpjefBal."> W/>            [namp;       [name] => text/pxt/"> W/>            [namp;       [name]ame] => /tmp/opt/lvotp/tehpeEwE87nfyu/>            [namp;       [namer, sigt; /tmp0/>            [namp;       [nameh ' gt; /tmp583/>            [namp;   &nbs />
    [1] p;       [nameatt(//&t; texty
        (            [namp;       [name] => /tmps-vas.txt/>            [namp;       [name] => text/pxt/plain/>            [namp;       [name]ame] => /tmp/opt/lvotp/tehpeEwEUBlvVz/>            [namp;       [namer, sigt; /tmp0/>            [namp;       [nameh ' gt; /tmp191/>            [namp;   &nbs />
    [1] p;   &nbs />
&nbs />
&nbs's the my snipper /> *?>?php
function rearrayFiles($files)
   
$fileads froman>= array(     $_FILESas $key=> $key[    $_FILSas $key=> $key) {
    $_FILe as $key=> $key=>br />    $fileads fro/n>[$key=>span>$i
=>span>$i] = $val=> />        <i;   }
        }
    }
   
$file_aryspan>as $val[    &nbsrn $fileads fro/n>[// shouprev pmisthe issue/>func />?>
down
212 -
Corecontato at dgmthiscom HereIuprefer sood="like:
&nbs/ class="default">?>?php
funcpublic tion reary( as <(p;$file_ary<" mupan>as < />&nbs />    $file_ary<" mupan>as < br />    $file_ary<" mu/n>[    &nbs />    'array_of_san>, 0as <(an>$file_ary<" mu/n>['name']);
    $file_ary<" mu/n>[    &nbs />    $ias $valy_keys($file['name']);
   
$file_key w to tan>= array(     $file/spspan>as $key=>br />    $file_ary<" mupan>as $key)$key=>br />    $file_key w to /n>[$key=>span>$i)$val=>pan>$key=>s />      &nbp; &nbs />  &nbp; &nbs />  &nbp; &nbsrn $file_ary[}
?>
down
14 -1
Corejavadscom Here$c         }                           
down
14 -3
CoreEric> HereT_llollojusrpa modificn setpof code:
buveaset. multiple filesetthe form langt type=ag,ILES['fie"s ][e"> ]sis/npuy.buveathensLES['fie"s ][e"> ]sis/s-v/npuy.'n multforms .the the sais/s (uetion </><tion &nbs />        &nbs/>       
    foreach ($i=0; $i?php$_ary    fore />            {
                    }
    }
&nbs/>    &nbsrn }
down
14 -3
Coreohcnimgmaihot dot com Hereb asimpe a"> >'n difncebuve'].p; &nbsFch exa4ple /></><LES['fielintype' elintype'<LES['fielintype' elintype'<LES['fielintype' elintype'
down
14 -15
CorePako> HereIu havewa/s fe ad moreiple file uplomaionce, remembhp "iple fil"tatg">buve /></><input type="file" multiple fil="iple fil"t="img[" mu/>ype="multipart/form-data">/
down
212 - 0
CoreRoal/> Heretion                         }        <i;   }
        }
    }
    }
<y
    &nbp; &nbs[0&t; texty
    retup;   &nbp; &nbs[es/no&t; texty
        <i;   }        <i;   }    retup;   &nb;i;   }    retup;   &nb;i;   }    retup;   &nb;i;   }    [1] p;   &nbs pa>    [1] [1&t; texty
    retup;   &nbp; &nbs[es/no&t; texty
    retup;   &nb;i;   }    retup;   &nb;i;   }    retup;   &nb;i;   }    retup;   &nb;i;   }    retup;   &nb;i;   }        {&nbs /n>
ref="/manual/voteadde.php?id=1secttures.file-upload.multiple&voteredirect=http://fr2?id=.netual/voteen/ures.file-upload.multiple&?id=">rimg src='/es/nos/s-voteadd@2x.png' alt='add aps-ve' width='12' height='12'>ronmonl>add aps-ve/n>monl>
en
>en