如何循环访问 $_FILES 数组?

2022-08-30 18:03:12

以下是我要循环访问的输入

Main photo:   <input type="file" name="image[]" />
Side photo 1: <input type="file" name="image[]" />
Side photo 2: <input type="file" name="image[]" />
Side photo 3: <input type="file" name="image[]" />

发生了一些奇怪的事情,当我上传任何东西时,我使用,我回显了该函数,它返回值5。该数组中不应有任何元素。为什么当我开始时只有4个文件时,有一个额外的输入?count($_FILES['image'])

现在,对于实际的循环本身,我尝试使用foreach循环,但它不起作用。

foreach($_FILES['image'] as $files){echo $files['name']; }

什么都没有出现,我最终想做的是遍历所有图像,确保它们的格式,大小正确,并重命名每个图像。但是这个简单的foreach()循环表明,不知何故,我甚至无法遍历$_FILES数组,而count()更让我感到困惑,因为它说数组中有5个元素,而我甚至没有上传任何东西。


答案 1

您的示例窗体应该可以正常工作。只是你期望超全局的结构与实际不同,当使用数组结构作为字段名称时。$_FILES

此多维数组的结构如下所示:

$_FILES[fieldname] => array(
    [name] => array( /* these arrays are the size you expect */ )
    [type] => array( /* these arrays are the size you expect */ )
    [tmp_name] => array( /* these arrays are the size you expect */ )
    [error] => array( /* these arrays are the size you expect */ )
    [size] => array( /* these arrays are the size you expect */ )
);

因此将产生.
但是,计算更深层次的维度也不会产生您可能期望的结果。例如,计算字段将始终导致文件字段的数量,而不是实际上传的文件数量。您仍然必须遍历元素,以确定是否已为特定文件字段上传了任何内容。count( $_FILES[ "fieldname" ] )5count( $_FILES[ "fieldname" ][ "tmp_name" ] )

编辑
因此,要遍历字段,您需要执行以下操作:

// !empty( $_FILES ) is an extra safety precaution
// in case the form's enctype="multipart/form-data" attribute is missing
// or in case your form doesn't have any file field elements
if( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) == 'post' && !empty( $_FILES ) )
{
    foreach( $_FILES[ 'image' ][ 'tmp_name' ] as $index => $tmpName )
    {
        if( !empty( $_FILES[ 'image' ][ 'error' ][ $index ] ) )
        {
            // some error occured with the file in index $index
            // yield an error here
            return false; // return false also immediately perhaps??
        }

        /*
            edit: the following is not necessary actually as it is now 
            defined in the foreach statement ($index => $tmpName)

            // extract the temporary location
            $tmpName = $_FILES[ 'image' ][ 'tmp_name' ][ $index ];
        */

        // check whether it's not empty, and whether it indeed is an uploaded file
        if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
        {
            // the path to the actual uploaded file is in $_FILES[ 'image' ][ 'tmp_name' ][ $index ]
            // do something with it:
            move_uploaded_file( $tmpName, $someDestinationPath ); // move to new location perhaps?
        }
    }
}

有关更多信息,请参阅文档


答案 2

只需以这种方式重命名您的字段

Main photo:   <input type="file" name="image1" />
Side photo 1: <input type="file" name="image2" />
Side photo 2: <input type="file" name="image3" />
Side photo 3: <input type="file" name="image4" />

然后,您将能够以通常的方式迭代它:

foreach($_FILES as $file){
  echo $file['name']; 
}

推荐