Cyber Sezar
Cyber Sezar

Reputation: 5

how to not upload empty file inputs

I have many file inputs in my HTML form. All of them are in an array.

For example :

<input type="file" name="attach[]">
<input type="file" name="attach[]">
<input type="file" name="attach[]">
<input type="file" name="attach[]">

How can I find empty inputs in PHP?

Upvotes: 0

Views: 100

Answers (3)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

All the fields (even the empty ones) get sent to the server and each field will have an array entry with its information (tmp_name, name, size, error, ...) although it's empty.

Just check $_FILES['attach']['error'][$i] against the UPLOAD_ERR_NO_FILE (int: 4) constant.

For more information about file upload error messages see the official PHP manual page.

Please note that for a bunch of files with the same name <input type="file" name="attach[]"> the array will look like this (in this case for three file input fields):

$_FILES['attach'] => array(
    'name' => array(
        0 => 'File 1.jpg',
        1 => 'File 2.pdf',
        2 => ''
    ),

    'error' => array(
        0 => 0,
        1 => 0,
        2 => 4
    ),

    'tmp_name' => array(
        0 => 'foo',
        1 => 'bar',
        2 => ''
    )

    // ...
)

Upvotes: 0

James Lalor
James Lalor

Reputation: 1246

I'd recommend checking the size, and if it's bigger than 0, then uploading it or handling it in the way you see fit

foreach($_FILES['attach']['size'] as $file) {
    if($file > 0) {
        // Upload
    }
}

Upvotes: 0

john
john

Reputation: 567

use this in your for each when you are uploading the file

<?php
if(!empty($_FILES['attach'][$i]))
{

//upload function

}

?>

Upvotes: 1

Related Questions