繁体   English   中英

服务器端表单验证PHP,带有多文件上传

[英]Server Side Form Validation PHP with multi-file Upload

HTML:

Owner: input type="text" name="owner[]" />
Category:
<select name="cat[]">
      <option value="clothes">Clothes</option>
      <option value="shoes">Shoes</option>
      <option value="accessories">Accessories</option>
</select>
Upload: <input type="file" name="image[]" />

可以在单击“ +”按钮时克隆相同字段的函数

我用以下方法计算POST字段:

$num = count($_FILES['image']['name']);

因为我想知道最终用户克隆字段的次数。

我想要的是确保用户必须用“ +按钮”填充他打开的所有字段,我不能检查所有隐藏的字段,而只想检查他打开的字段。

那我该怎么办?

我不能这样做:

$owner = $_POST['owner'][$i];
$cat = $_POST['cat'][$i];
$file = $_FILES['image'][$i];

if ($owner && $cat && $file)
   echo "bla bla bla";
else
   echo "fill all the fields!";

谁能帮我 ?

谢谢

您需要事先确定一些要点。 每当您将任何输入字段的name属性用作“ owner[] ”或“ cat[] ”或“ image[] ”时,都将得到一个数组。 但是由于默认情况下输入文件的属性访问功能已经是2D数组,因此现在您将能够将这些属性作为3D数组进行访问。

在输入文件字段的name属性中添加“ [] $_FILES['image'][0]['name'] ”后,由于数组索引开始,因此您将获得第一个文件的名称为“ $_FILES['image'][0]['name'] ”与0。根据您的问题,您可以使用以下方式进行验证:-

<?php
$numOwners = count($_POST['owner']);
$numCats = count($_POST['cat']);
$numFiles = count($_FILES['image']);

// Check to see if the number of Fields for each (Owners, Categories & Files) are the same
if ($numFiles === $numCats && $numFiles === $numOwners) {
    $boolInconsistencyOwners = FALSE;
    $boolInconsistencyCats = FALSE;
    $boolInconsistencyFiles = FALSE;

    for ($i = 0; $i < $numFiles; $i++) {
        if (empty($_POST['owner'][$i])) {
            $boolInconsistencyOwners = TRUE;
            break;
        }

        if (empty($_POST['cat'][$i])) {
            $boolInconsistencyCats = TRUE;
            break;
        }

        if (!is_uploaded_file($_FILES['image'][$i]['tmp_name'])) {
            $boolInconsistencyFiles = TRUE;
            break;
        }
    }

    if ($boolInconsistencyOwners || $boolInconsistencyCats || $boolInconsistencyFiles) {
        echo "I knew that there will be some problems with users' mentality!";
        // Redirect with proper Error Messages
    }
    else {
        echo "Wow, Users have improved & have become quite obedient!";
        // Proceed with normal requirements
    }
}
else {
    echo "Something fishy is going on!";
}
?>

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM