在变量中存储表单元素ID?

时间:2012-11-29 10:09:46

标签: php forms file file-upload html-form

我有一个 HTML 表单,其中包含以下代码:

<input id="image_22" name="images[]" type="file"  />
<input id="image_8" name="images[]" type="file"  />   

我希望能够将表单输入ID元素存储在变量中(例如$ imgnumber ='image_22')。这可能吗?请参阅以下代码中的评论:

PHP:

for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
        $number_of_file_fields++;
        if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not
            $number_of_uploaded_files++;
            $uploaded_files[] = $_FILES['images']['name'][$i];

            if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) {

                $number_of_moved_files++;
                // *** COMMENT *** // 
                $imgnumber = CURRENT_FILE_INPUT_ID - this would store e.g. "image_22"
                }

            }

    }

非常感谢您提供的任何帮助: - )

2 个答案:

答案 0 :(得分:2)

仅将name和输入值提交给服务器端。您可以将ID编码到名称中,而不是使用文件数组。

<input id="image_22" name="image_22" type="file"  />
<input id="image_8" name="image_8" type="file"  />

访问PHP端:

foreach($_FILES as $imageName => $file)
{
    // $imageName contains image_22 or image_8
    // $file contains the full array for this particular file
}

修改

您更新的PHP代码可能是:

foreach($_FILES as $imageName => $file)
{
    $number_of_file_fields++;
    if ($file['name'] != '') { //check if file field empty or not
        $number_of_uploaded_files++;
        $uploaded_files[] = $file['name'];

        if (move_uploaded_file($file['tmp_name'], $upload_directory . $file['name'])) {

            $number_of_moved_files++;
            // *** COMMENT *** // 
            $imgnumber = $imageName; // image_22 or image_8
        }
    }
}

如果不这样做,您必须将ID作为单独的变量发送,例如使用隐藏输入或查询字符串。

答案 1 :(得分:1)

您无法在纯HTML + PHP中执行此操作,原因很简单,因为浏览器在提交表单时不会向服务器发送ID。

最明显的解决方案是在其他地方添加相关信息,例如name属性。

<强>更新

而不是:

<input id="image_22" name="images[]" type="file"  />
<input id="image_8" name="images[]" type="file"  />

......这样做:

<input name="images[22]" type="file"  />
<input name="images[8]" type="file"  />

<强>更新

如果你print_r()输入,你会看到它的样子:

Array
(
    [images] => Array
        (
            [name] => Array
                (
                    [22] => Test.txt
                    [8] => Blah.exe
                )

            [type] => Array
                (
                    [22] => text/plain
                    [8] => application/octet-stream
                )

            [tmp_name] => Array
                (
                    [22] => D:\Server\PHP\tmp\php7D2D.tmp
                    [8] => D:\Server\PHP\tmp\php7D4E.tmp
                )

            [error] => Array
                (
                    [22] => 0
                    [8] => 0
                )

            [size] => Array
                (
                    [22] => 3695
                    [8] => 432
                )

        )

)