Jurgen
Jurgen

Reputation: 274

Multiple file upload issue (simple php/html)

The only issue with the code below - it creates one record if no image was selected. It's not supposed to proceed the code if no one image is chosen. This method works fine with single type image form.

if(!empty($_FILES['gallery']['name'])) {
            for ($i=0; $i < count($_FILES['gallery']['tmp_name']); $i++) { 
            $gallery_tmp = $_FILES['gallery']['tmp_name'][$i];
            $gallery = time().$_FILES['gallery']['name'][$i];
            move_uploaded_file($gallery_tmp, "../uploads/$gallery");
            $sql = mysqli_query($database->connection, "INSERT INTO gallery (img) VALUES ('$gallery')");
            }
        }

HTML code is below:

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="gallery[]" class="form-control" multiple="multiple">
<input type="submit" name="submit" value="Update" class="">
</form>

Upvotes: 2

Views: 77

Answers (2)

kolorafa
kolorafa

Reputation: 109

Even if you don't send any images your $_FILES['gallery']['name'] is not empty, it cointain 1 element with empty name.

You could do a dirty hack by checking if first elemetn is not empty:

if(!empty($_FILES['gallery']['name'][0])) {

But you should really check if it's empty inside the loop.

Also don't trust user input by doing

$gallery = time().$_FILES['gallery']['name'][$i];
move_uploaded_file($gallery_tmp, "../uploads/$gallery");

Someone could name a file test.php and upload you code, or set in name "../../index.php and override your index.php :)

Upvotes: 1

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

Added condition that if image not uploaded, its record won't be inserted to database.

Updated Code:

if(!empty($_FILES['gallery']['name'])) {
    for ($i=0; $i < count($_FILES['gallery']['tmp_name']); $i++) { 
        $gallery_tmp = $_FILES['gallery']['tmp_name'][$i];
        $gallery = time().$_FILES['gallery']['name'][$i];
        $is_uploaded = move_uploaded_file($gallery_tmp, "../uploads/$gallery");

        if( $is_uploaded == TRUE ) {
            $sql = mysqli_query($database->connection, "INSERT INTO gallery (img) VALUES ('$gallery')");
        }
    }
}

Upvotes: 1

Related Questions