在for循环期间将文件输入ID存储在变量内PHP

时间:2012-11-28 15:04:22

标签: php html file file-upload for-loop

我正在使用以下HTML&用于将多个图像移动到我的服务器的PHP代码。

有没有办法使用我的代码,我可以将特定的输入元素与上传的文件相关联?

因此,在我的 for循环中,我可以发现何时正在处理来自“ image_22 ”的图片。这可以使用我当前的代码吗?

梦想世界会将值“image_22”存储在变量 $ imageNum 中: - )

以下是我目前正在处理的内容片段......

HTML:

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

PHP:

<?php
    if (isset($_POST['Submit'])) {
    $number_of_file_fields = 0;
    $number_of_uploaded_files = 0;
    $number_of_moved_files = 0;
    $uploaded_files = array();
    $upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory


    /**
     * we get a $_FILES['images'] array ,
     * we procee this array while iterating with simple for loop
     * you can check this array by print_r($_FILES['images']);
     */
    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++;
            }

        }

    }
    echo "Number of File fields created $number_of_file_fields.<br/> ";
    echo "Number of files submitted $number_of_uploaded_files . <br/>";
    echo "Number of successfully moved files $number_of_moved_files . <br/>";
    echo "File Names are <br/>" . implode(',', $uploaded_files);
    }
    ?> 

谢谢!

1 个答案:

答案 0 :(得分:5)

在您的HTML中,只需将该值包含在[]

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

在循环中,使用带有索引的foreach而不是增量for循环,这是PHP中比增量类型更常见的模式。 $index将是[]中提供的数字:

// Loop over the ['name'] key in $_FILES['images'] to get all the named indexes
foreach ($_FILES['images']['name'] as $index => $filename) {

  if ($filename != '') {
     // not empty...
     $number_of_uploaded_files++;

     // Check for validity (see below)...

     // Use the name concatenated with _$index to supply store the index with the filename
     $uploaded_files[] = $filename . "_$index";
     if (move_uploaded_file($_FILES['images']['tmp_name'][$index], $upload_directory . $filename . "_$index")) {
       // successful rename
       $number_of_moved_files++;
     }
  }
}

请注意,您的脚本目前容易受到路径注入攻击。您必须过滤每个文件的name以防止包含../之类的内容,这些内容可能会强制将文件保存在文件系统的任何位置(Web服务器可写)!建议使用可接受值的正则表达式检查名称:

// Verify that the uploaded filename contains only letters, numbers, hyphen, underscore, space before the `.` and letters only after the `.`
// You could also insist that it end in `.(jpg|gif|png)` or whatever your acceptable formats are
// Most important is to prevent things like `../`
if (preg_match('/^[a-z0-9_- ]+\.[a-z]+$/i', $filename)) {
  // It's an ok filename
}