2016-12-26 45 views
0

我有多个输入字段具有相同的名称。他们看起来像:PHP通过输入字段名称相同的循环,全部上传

<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[]" /> 
... 
... 

我这个代码上传:

<?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); 
    }; 
?> 

的问题是,这个代码将只上载第一个输入字段的画面。

如何重写我的代码以上传所有输入字段? (我知道我必须在这种情况下给我的文件唯一的名称,但那不是我的问题。我想知道如何告诉PHP它必须遍历所有输入字段并执行上传。 !前进

+0

只需循环变量'$ _POST ['image-to-upload']'。它是一个数组,因此您可以查看其中的所有项目。 – Dekel

+0

好的,谢谢。但我不知道该怎么做:/试图找出它,但我不明白 – Maxischl

+0

在谷歌搜索“通过数组的PHP循环”给出了第一个结果:http://php.net /manual/en/control-structures.foreach.php – Dekel

回答

1

使用foreach循环:

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

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

在您的例子 - 你的阵列的名字是$_POST['image-to-upload']这样你就可以在它的循环:

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); 
} 
0

对于迭代中的所有文件使用foreach循环

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

     //Code 

    } 

请参阅此链接更多的理解:

PHP Multiple File Array

+0

你读过这个问题吗?这与多个文件上传完全无关 – Dekel

0

声明数组并等同于您的文章数据,如$arr =new array(); $arr = $_POST["img[]"]; 与一个for循环,你可以通过你的数组循环

相关问题