Durian Nangka
Durian Nangka

Reputation: 255

Get keys of $_FILES array

Is there any way of getting the keys of the file upload input field named upload[] after form submission?

    <input type="file" name="upload[3]" />
    <input type="file" name="upload[7]" />
    <input type="file" name="upload[10]" />

Upvotes: 2

Views: 2827

Answers (3)

silentcoder
silentcoder

Reputation: 1048

use $_FILES["upload"] to get the keys. for more information

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="upload[3]" />
    <input type="file" name="upload[7]" />
    <input type="file" name="upload[10]" />
    <input type="submit" />
</form>
    <?php
    echo "<pre>"; print_r($_FILES['upload']);
}
?>

Output is

Array
(
    [name] => Array
        (
            [3] => Chrysanthemum.jpg
            [7] => 
            [10] => 
        )

    [type] => Array
        (
            [3] => image/jpeg
            [7] => 
            [10] => 
        )

    [tmp_name] => Array
        (
            [3] => D:\xampp\tmp\phpD249.tmp
            [7] => 
            [10] => 
        )

    [error] => Array
        (
            [3] => 0
            [7] => 4
            [10] => 4
        )

    [size] => Array
        (
            [3] => 879394
            [7] => 0
            [10] => 0
        )

)

Upvotes: 2

Marc B
Marc B

Reputation: 360662

Since you're using the array naming hack, note that $_FILES is built in an incredibly moronic way, you'll get this structure:

$_FILES = array(
   'upload' => 
        'name' => array(
           '3' => 'name of file #3',
           '7' => 'name of file #7', 
           etc...
        ),
        'type' => array(
           '3' => 'mime type of file #3',
           etc...
       etc..
    );

To retrieve the 3,7,etc.. keys, you'll need array_keys($_FILES['upload'])

Don't know what the PHP devs were smoking that day, but $_FILES['upload'][3]['name'] SHOULD have been the structure... All of a file's data in a single child array, not spread across 6 different ones.

Upvotes: 3

Ravi Hirani
Ravi Hirani

Reputation: 6539

array_keys will give you all keys.

$keys = array_keys($_FILES["upload"]);

Upvotes: 7

Related Questions