PHP没有检测文件输入值

时间:2015-03-20 15:13:08

标签: php mysql forms input mysqli

我正在尝试创建一个用户可以插入多个图像的表单。但是,当文件输入为空时,类函数(addImgToNieuws)仍然会运行。

以下是代码:

if($_POST && !empty($_POST['title']) && !empty($_POST['description']) ) {
    $response = $mysql->addNieuwsItem(
        $_POST['title'], 
        $_POST['description'],
        $id
    );

    if(!empty($_FILES['images']) && $_FILES['images']['error'] != 4){
        $response = $mysql->addImgToNieuws(
            $_FILES['images']
        );
    }
}

表格:

<form action='' method='post' enctype='multipart/form-data' />
    <input type='text' name='title' placeholder='Titel' />
    <textarea name='description' placeholder='Descriptie'></textarea>
    <input type='file' name='images[]' multiple />
    <input type='submit' name='submit' value='Plaatsen' />
</form>

班级功能:

function addImgToNieuws($images){
    echo 'Function runs';
}

编辑:它是否与它作为数组发布的事实有关?

3 个答案:

答案 0 :(得分:1)

由于您正在进行多个文件上传$_FILES['images']将成为一个数组,因此您需要相应地处理每个图像上传和错误陷阱。

然而,看起来好像你的addImgToNieuws()方法一次处理整个$_FILES['images']数组,而不是多次调用它,只记录(或捕获/输出)任何失败可能更好。

if(!empty($_FILES['images'])) {

    $aErrors = array();
    foreach($_FILES['images'] as $aThisImage) {

        // capture any errors
        // I've put the current $_FILES['images'] array into the errors
        // array so you can check the ['name'], ['tmp_name'] or ['error']
        // for each individually
        if($aThisImage['error'] !== UPLOAD_ERR_OK) { 
            $aErrors[] = $aThisImage;
        }
    }

    //check the errors
    if($aErrors) {
        // take appropriate action for your app knowing that
        // there has been a problem with *some* images
    }

    //no errors
    else {
        $response = $mysql->addImgToNieuws(
            $_FILES['images']
        );
    }
}

答案 1 :(得分:0)

试试这个

 if(!empty($_FILES['images']) && $_FILES['images']['error'] != 4 && $_FILES['images'] != ''){

答案 2 :(得分:0)

你可以这样试试:

if(isset($_POST['submit']) && isset($_POST['title']) && isset($_POST['description']) ) {
    $response = $mysql->addNieuwsItem(
        $_POST['title'], 
        $_POST['description'],
        $id
    );

    if(is_uploaded_file($_FILES['images']['tmp_name'])){
        $response = $mysql->addImgToNieuws(
            $_FILES['images']
        );
    }
}