2

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>

2 Answers 2

1

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution works good. I'm not sure about the security issues. I'm quite new on programming and I'm just making some projects for myself education. I do not check for any extension of the uploading files. But later I should add this functionality.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.