PHP 未检测到文件输入值

PHP not detecting file input value

我正在尝试创建一个用户可以插入多张图片的表单。然而,当文件输入为空时,class 函数 (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>

class函数:

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

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

试试这个

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

你可以这样试试:

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']
        );
    }
}

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

但是看起来您的 addImgToNieuws() 方法一次处理了整个 $_FILES['images'] 数组,因此与其多次调用它不如只记录(或 capture/output ) 任何失败。

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']
        );
    }
}