如何修复PHP“为Foreach()提供的无效参数”

问题描述 投票:0回答:3
<?php
include "config.php";
if(isset($_FILES['berkas'])){
    foreach ($_FILES['berkas']['name'] as $file=>$name){
        $filename = date('Ymd-His',time()).mt-rand().'-'.$name;
        try{
            if(move_uploaded_file($_FILES['berkas']['tmp_name'][$file], 'uploads/'.$filename));{
                $stmt= $db->prepare("insert into multipleload values('',?)");
                $stmt ->bindParam(1,$filename);
                $stmt->execute();

            }
        } catch (Exception $e){
            echo $e;
        }

    }
}   
?>

错误在第3行我已经尝试了if(is_array()){}但它没有停止错误消息。

我正在尝试制作文件提交php文件顺便说一句。我查看了以前的帖子,并且真的发现它显然没有得到数组。

php
3个回答
1
投票

foreach期望循环的变量是array。而且似乎$_FILES['berkas']['name']不是一个数组,它代表一个文件名的字符串。你应该像这样使用它

foreach ($_FILES['berkas'] as $file => $name ){ 
    // your code here 
}

1
投票

这是因为$_FILES的结构如下:

$_FILES[fieldname] => array(
    [name] => array( /* these arrays are the size you expect */ )
    [type] => array( /* these arrays are the size you expect */ )
    [tmp_name] => array( /* these arrays are the size you expect */ )
    [error] => array( /* these arrays are the size you expect */ )
    [size] => array( /* these arrays are the size you expect */ )
);

因此,当您尝试迭代_FILES时,您提供的数组与关联数组相反。相反,你的foreach应该是这样的:

foreach ($_FILES['berkas'] as $type=>$value) {
    // if $type is 'name', do something
}

如果你试图迭代这个名字,你可以做到

foreach ($_FILES['berkas']['name'] as $name) {
    // if $type is 'name', do something
}

0
投票

你可能想循环遍历$ _FILES超全局,如下所示:

foreach ($_FILES as $file => $data) {

其中$data将是一个包含键'name','type','size'等的数组。有关其工作原理的更多信息,请参阅http://php.net/manual/en/features.file-upload.post-method.php

© www.soinside.com 2019 - 2024. All rights reserved.