Загрузка на сервер нескольких файлов

Загрузку нескольких файлов можно реализовать используя, например, различные значения name для тега input.

Также предусмотрена возможность автоматического получения организованной в массив информации о нескольких одновременно загружаемых файлах. Для реализации такой возможности используйте тот же синтаксис отправки массива из HTML-формы, что и для множественных полей select и checkbox:

Замечание: Поддержка загрузки нескольких файлов была добавлена в PHP 3.0.10.

Пример 38-3. Загрузка нескольких файлов

<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>

В случае, если такая форма была отправлена, массивы $_FILES['userfile'], $_FILES['userfile']['name'], и $_FILES['userfile']['size'] будут инициализированы (точно так же, как и $HTTP_POST_FILES для PHP 4.1.0 и более ранних версий). Если конфигурационная директива register_globals установлена значением on, также будут инициализированы сопутствующие глобальные переменные. Каждая из таких переменных будет представлять собой численно индексированный массив соответствующих значений для принятых файлов.

Например, предположим, что были загружены файлы /home/test/review.html и /home/test/xwp.out. В таком случае переменная $_FILES['userfile']['name'][0] будет установлена значением review.html, а переменная $_FILES['userfile']['name'][1] - значением xwp.out. Аналогично, переменная $_FILES['userfile']['size'][0] будет содержать размер файла review.html и так далее.

Переменные $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0] и $_FILES['userfile']['type'][0] также будут инициализированы.



Загрузка на сервер нескольких файлов
Bob Doe
08-Aug-2005 02:17
Here is a the simple test form I needed, pieced togther from 2 or 3 posts in the documentation elsewhere.

<html>
<head>
<title>HTML Form for uploading image to server</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
//places files into same dir as form resides
foreach ($_FILES["pictures"]["error"] as $key => $error) {
   if (
$error == UPLOAD_ERR_OK) {
       echo
"$error_codes[$error]";
      
move_uploaded_file(
        
$_FILES["pictures"]["tmp_name"][$key],
        
$_FILES["pictures"]["name"][$key]
       ) or die(
"Problems with upload");
   }
}
?>
</body>
</html>
28-Jul-2005 07:50
re: phpuser's comment

I found that if instead of the form structure at the top of the page use one like this:

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

Notice the names are unique and not an array element.  Now the array is structured more like phpuser would like. I did this and used...

foreach ($_FILES as $file) { ... }

without issue.
sgoodman_at_nojunk_immunetolerance.org
17-Jun-2005 07:03
Re: phpuser_at_gmail's comment, a simpler way to have create that data structure is to name your HTML file inputs different names. If you want to upload multiple files, use:
<input type=file name=file1>
<input type=file name=file2>
<input type=file name=file3>
etc...
Each field name will be a key in the $_FILES array.
bishop
02-Jun-2005 11:27
Elaboration on phpuser at gmail dot com reArrayFiles() function (which assumed sequential, integer keys and uni-dimensional), this function will work regardless of key and key depth:

<?php
// information grouper
function groupFileInfoByVariable(&$top, $info, $attr) {
   if (
is_array($info)) {
       foreach (
$info as $var => $val) {
           if (
is_array($val)) {
              
groupFileInfoByVariable($top[$var], $val, $attr);
           } else {
              
$top[$var][$attr] = $val;
           }
       }
   } else {
      
$top[$attr] = $info;
   }

   return
true;
}

// usage
$newOrdering = array ();
foreach (
$_FILES as $var => $info) {
   foreach (
array_keys($info) as $attr) {
      
groupFileInfoByVariable($newOrdering, $info[$attr], $attr);
   }
}

// $newOrdering holds the updated order
?>
phpuser at gmail dot com
26-May-2005 08:09
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'];
   }
}

?>

<Наиболее распространенные ошибкиПоддержка метода PUT>
 Last updated: Mon, 14 Nov 2005