9阅网

您现在的位置是:首页 > 知识 > 正文

知识

php - 如何在php中上传并插入多张图片与表单输入?

admin2022-11-07知识17

控制器:

if($_POST)
{
    $filename = $_FILES['file']['name'];
    $temp = explode(".", $filename);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $array = array("jpg","jpeg","png");
    $PATH = "public/images/users/";
    if(in_array($ext,$array)){
        if(move_uploaded_file($_FILES['file']['tmp_name'],  $PATH.$newfilename)){
            $data = array(
                "name" => $this->input->post('name'),
                "image_gallery" => $newfilename
            );
            $insert = $this->db->insert('product',$data);
        }else{
            echo $this->lang->line('notUpload');
        }
    }else{
        echo $this->lang->line('extNotMatch');
    }
}

view:

<?php echo $this->session->flashdata('success'); ?>
<form method="post" enctype="multipart/form-data">
    <div>
        <div>
            <input type="text" id="name" name="name" placeholder="Name">
            <input type="file" id="files" name="files[]" multiple/>
            <button type="submit" id="submit" name="submit">Submit</button>
        </div>
    </div>
</form>

在这段代码中,我只是简单地创建了一个表单,并希望插入表单数据和多张图片,但我得到了一个错误信息

消息:explode()期望参数2为字符串,给定数组。

消息:pathinfo()期望参数1为字符串,给定数组。

我还想 change name of uploaded image. 那么,我该怎么做呢?请帮帮我。

谢谢你的帮助



【回答】:

修改你的控制器代码如下。

if($_POST)
{
    $total = count($_FILES['files']['name']);
    for( $i=0 ; $i < $total ; $i++ ) {
        $filename = $_FILES['files']['name'][$i];
        $temp = explode(".", $filename);
        $newfilename = round(microtime(true)) . '.' . end($temp);
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        $array = array("jpg","jpeg","png");
        $PATH = "public/images/users/";
        if(in_array($ext,$array)){
            if(move_uploaded_file($_FILES['files']['tmp_name'][$i],  $PATH.$newfilename)){
                $data = array(
                    "name" => $this->input->post('name'),
                    "image_gallery" => $newfilename
                );
                $insert = $this->db->insert('product',$data);
            }else{
                echo $this->lang->line('notUpload');
            }
        }else{
             echo $this->lang->line('extNotMatch');
        }
    }
}
【回答】:

explode 将取一个字符串并使用 delimiter 参数来分割成碎片。在原文中,因为您使用的是 multiple 以允许多个文件 $_FILES['file']['name'] 本身就变成了一个数组。同样的问题也影响了 pathinfo 调用,所以你需要使用不同的语法来访问文件数据。如果你在循环开始时创建变量,你可以避免这样的问题。

if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES[ $fieldname ] ) ){

    $errors=array();

    $allowed=array( "jpg", "jpeg", "png" );
    $path='public/images/users/';
    $fullpath=__DIR__ . '/' . $path;

    $fieldname='file';


    # multiple files require a slightly odd syntax to access each file
    foreach( $_FILES[ $fieldname ]['name'] as $i => $void ) {

        if( !empty( $_FILES[ $fieldname ]['tmp_name'][$i] ) ) {
            $name = $_FILES[ $fieldname ]['name'][$i];
            $size = $_FILES[ $fieldname ]['size'][$i];
            $type = $_FILES[ $fieldname ]['type'][$i];
            $tmp  = $_FILES[ $fieldname ]['tmp_name'][$i];
            $error= $_FILES[ $fieldname ]['error'][$i];

            $ext  = pathinfo( $name, PATHINFO_EXTENSION );
            list( $width, $height, $type, $attr ) = getimagesize( $tmp );
            /*
                other tests - check mime type? size?
            */


            if( in_array( $ext, $allowed ) ){
                /*
                    using the full path rather than a relative path
                    is, in my opinion, more reliable - hence __DIR__
                */
                $filename=sprintf('%s.%s',round(microtime(true)),$ext);
                $filepath=sprintf('%s%s',$fullpath,$filename);
                $displaypath=sprintf('%s%s',$path,$filename);

                $status=move_uploaded_file( $tmp, $filepath );
                if( $status ){
                    $data=[
                        'name'          =>  $this->input->post('name'),
                        'image_gallery' =>  $displaypath
                    ];
                    $insert = $this->db->insert('product',$data);

                }else{
                    $errors[$name][]=$this->lang->line('notUpload');
                }
            }else{
                $errors[$name][]=$this->lang->line('extNotMatch');
            }
        }
    }
    if( !empty( $errors ) ){
        foreach($errors as $name => $arr){
            printf('<h1>%s</h1><pre>%s</pre>',$name,print_r($arr,true));
        }
    }
}