maxischl
maxischl

Reputation: 631

PHP loop through input fields with same name, upload all

I have multiple input fields with the same name. they look like:

<input type="hidden" class="image-hidden" name="image-to-upload[]" />
<input type="hidden" class="image-hidden" name="image-to-upload[]" />
<input type="hidden" class="image-hidden" name="image-to-upload[]" />
<input type="hidden" class="image-hidden" name="image-to-upload[]" />
...
...

I am uploading with this code:

<?php
    if(isset($_POST['new-blogpost'])) {
        $img = $_POST['image-to-upload'][0];
        $img = str_replace('data:image/jpeg;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $file = 'image.jpg';
        $success = file_put_contents($file, $data);
    };
?>

the problem is, this code will only upload the first input fields picture.

How do I have to rewrite my code to upload all input fields? (I know that I have to give my files unique names in that case, but thats no my question. I'm wondering how to tell PHP it has to loop through all the input fields and do the upload.

Thanks in advance!

Upvotes: 0

Views: 1703

Answers (3)

Yusif
Yusif

Reputation: 31

Declare an array and equate it to your post data like $arr =new array(); $arr = $_POST["img[]"]; and with a for loop you can loop through your array

Upvotes: 0

Dekel
Dekel

Reputation: 62556

Use a foreach loop:

$list = ['apple', 'banana', 'cherry'];

foreach ($list as $value) {
    if ($value == 'banana') {
        continue;
    }
    echo "I love to eat {$value} pie.".PHP_EOL;
}

In your example - your array's name is $_POST['image-to-upload'] so you can loop over it:

foreach($_POST['image-to-upload'] as $img) {
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    // $file = 'image.jpg'; // here you need to create the unique filename
    $success = file_put_contents($file, $data);
}

Upvotes: 1

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

For iterating all the files use foreach loop

foreach($_FILES['image-to-upload']['tmp_name'] as $key => $tmp_name)
    {

      //Code

    }

See this link for more understanding:

PHP Multiple File Array

Upvotes: 0

Related Questions