views:

147

answers:

3

var_dump($_FILES) gives the following:

array
  'test1' => 
    array
      'name' => 
        array
          'f' => string 'ntuser.dat.LOG' (length=14)
      'type' => 
        array
          'f' => string 'application/octet-stream' (length=24)
      'tmp_name' => 
        array
          'f' => string 'D:\wamp\tmp\php223.tmp' (length=22)
      'error' => 
        array
          'f' => int 0
      'size' => 
        array
          'f' => int 0

Why is http designed this way?How can I process the array efficiently(sometimes means no looping?) so I can get the file by $_FILES['test1']['f']?

+1  A: 

Seems to be pretty straightforward:

$filepath = $_FILES["test1"]["tmp_name"]["f"];
Pekka
+4  A: 

I guess input fields with type file are not meant to be used with array like names. Use

 <input type="file" name="test1_f" />

instead and access with $_FILES['test1_f'].

Otherwise you cannot access the single attributes of the file without looping.

Maybe you can show us how you create the input elements and how you want to process the $_FILES array in order to provide a better solution.

Update:
I have to redraw my statement partially. As described here, PHP supports HTML array feature also for files. But the point with this is, that the files on the server side should be processed as a whole.
They also provide a nice example how too deal with, maybe it helps you:

foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}

If you want to have access to a single file, then you just use the wrong approach.

Felix Kling
+1 You could reshuffle the array somehow but I would go with this suggestion - way easier.
Pekka
yeah, so one can just foreach over $_FILES. very handy
Col. Shrapnel
A: 

Here is the solution:

  static public function convertFileInformation(array $taintedFiles)
  {
    $files = array();
    foreach ($taintedFiles as $key => $data)
    {
      $files[$key] = self::fixPhpFilesArray($data);
    }
    return $files;
  }
  static protected function fixPhpFilesArray($data)
  {
    $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
    $keys = array_keys($data);
    sort($keys);
    if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name']))
    {
      return $data;
    }
    $files = $data;
    foreach ($fileKeys as $k)
    {
      unset($files[$k]);
    }
    foreach (array_keys($data['name']) as $key)
    {
      $files[$key] = self::fixPhpFilesArray(array(
        'error'    => $data['error'][$key],
        'name'     => $data['name'][$key],
        'type'     => $data['type'][$key],
        'tmp_name' => $data['tmp_name'][$key],
        'size'     => $data['size'][$key],
      ));
    }
    return $files;
  }