计算在多个文件字段中选择上传的文件数

时间:2015-09-30 19:10:44

标签: php

我写了一个脚本,用户可以选择将多个图像上传到表单。我阻止用户提交表单,直到所有已添加的文件字段实际包含要上载的文件。

EG:

用户有三个要填写的文件字段,因此必须准备好三个文件才能提交到数据库。

我在每个文件上传字段中使用相同的ID。当我使用print_r($_FILES);时,它会返回一个数组。如果我在第一个文件字段中浏览文件,并留下另外两个空白,则会声明[1]和[2]的数组对象为空,但[0]显然会有名称,类型,大小等因为它存在。

我如何确保使用PHP实际填写所有文件字段?

提前致谢,Rich

到目前为止,我的努力是:

$imgName1 = $_FILES['upload1']['name'];
$imgTmp1 = $_FILES['upload1']['tmp_name'];
$imgType1 = $_FILES['upload1']['type'];
$imgSize1 = $_FILES['upload1']['size'];

print_r($_FILES);

if(!$imgTmp1){
echo "<span class='error'>You need to include at least one image with this article.</span>";    
exit();

} else {

$fileCount=($_FILES['upload1']['name']); // My attempt to count that the file fields are all filled in

$cnt = $_POST['cnt']; // This is the number of file fields that currently exist

echo "<br/>";

echo count($fileCount);
if($cnt != $fileCount){
echo "<span class='error'>You have not uploaded all of your files.</span>";
exit();
}

// etc etc

1 个答案:

答案 0 :(得分:0)

您的上传检查不正确。 $ _FILES中存在的东西并不意味着上传了文件。上传失败将仍然会创建$ _FILES条目。

您需要检查是否存在$ _FILES条目及其error参数:

if (isset($_FILES['upload1'])) { 
    if ($_FILES['upload']['error'] === UPLOAD_ERR_OK) {
       ... file was successfully uploaded
    } else {
       ... upload failed
    }
} else {
    ... no file upload was even attempted
}