0

If I do something like this to get handle file uploads:

if ($_FILES) {
    foreach ($_FILES as $file) {
        //...Handle the upload process
    }
}

Is there any way that I can get the key of the file? As in:

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

I want to know that the file is coming from "myfile".

Edit: The obvious solution to this turns out to be:

foreach($_FILES as $key => $file) {

    $input_name = $key;
    // Handle upload.

}
2
  • In your HTML, I believe that you'll want to use <input type="file" name="myfile[]" /> (note the []) to make is easier to understand the multiple files. Commented Jul 21, 2011 at 22:26
  • Done. @eric, actually it's for multiple elements, if that makes sense. <input type="file" name="file1" /> <input type="file" name="file2" /> Commented Jul 23, 2011 at 17:48

1 Answer 1

1

If the input name in your form is myfile, then it will be in the $_FILES array as:

$_FILES['myfile']

So you can do:

foreach ($_FILES as $inputName => $fileInfo) {

}

Check out Handling file uploads for more info.

Sign up to request clarification or add additional context in comments.

3 Comments

So I can actually do this? list($key,$value) = each($_FILES)
yeah I get that, but specifically I want to have the key of the form input. So something like this while(list($key,$file) = each($_FILES)){ echo 'the key is: ' . $key; }
Yes that will work. $key will then contain the name your chose for your form input. I've also edited the answer to make it more clear with the foreach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.