PHP上传图片但不插入数据库

时间:2018-03-06 07:44:01

标签: php

期望的结果: 能够一次上传多个图像,每个图像上传到上传文件夹并将图像路径/名称存储在数据库中。

目前的结果: 能够将多个图像上传到“上传”文件夹,但只插入一个图像路径/名称期间,即使尝试在初始文件夹之后上传也是如此。

我很困惑为什么会这样做,以及如何有效地解决它。

    if(isset($_POST["sendimage"])){     
    $errors = array();

    $extension = array("jpeg","jpg","png","gif");

    $bytes = 15284;
    $allowedKB = 15284;
    $totalBytes = $allowedKB * $bytes;

    if(isset($_FILES["files"])==false)
    {
        echo "<b>Please, Select the files to upload!!!</b>";
        return;
    }

    $conn = mysqli_connect("localhost","root","","testDB"); 

    foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
    {
        $uploadThisFile = true;

        $file_name=$_FILES["files"]["name"][$key];
        $file_tmp=$_FILES["files"]["tmp_name"][$key];

        $ext=pathinfo($file_name,PATHINFO_EXTENSION);

        if(!in_array(strtolower($ext),$extension))
        {
            array_push($errors, "File type is invalid. Name:- ".$file_name);
            $uploadThisFile = false;
        }               

        if($_FILES["files"]["size"][$key] > $totalBytes){
            array_push($errors, "File size must be less than 100KB. Name:- ".$file_name);
            $uploadThisFile = false;
        }

        if(file_exists("upload/".$_FILES["files"]["name"][$key]))
        {
            array_push($errors, "File is already exist. Name:- ". $file_name);
            $uploadThisFile = false;
        }

        if($uploadThisFile){
            $filename=basename($file_name,$ext);
            $newFileName=$filename.$ext;                
            move_uploaded_file($_FILES["files"]["tmp_name"][$key],"upload/".$newFileName);

            $query = "INSERT INTO uploads(image_path, image_name) VALUES('upload','".$newFileName."')";

            mysqli_query($conn, $query);            
        }
    }

    mysqli_close($conn);

    $count = count($errors);

    if($count != 0){
        foreach($errors as $error){
            echo $error."<br/>";
        }
    }       
}

这段代码工作得非常好直到我不得不重新建模我的数据库,以便将图像名称/路径上传到另一个表中而不是其他信息。 &#34;其他信息&#34;是图像上传脚本上方的代码,PDO语句是为了从表单

发送输入

1 个答案:

答案 0 :(得分:0)

上述代码看起来或多或少是正确的(除了100Kb文件大小限制计算),据我所知,但也许以下可能有用。

我将代码转换为使用prepared statement - 在循环中多次调用相同的查询时,这是一种更有效的方法。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'testDB';



        if( isset( $_POST['sendimage'] ) ){

            $errors = array();
            $uploads= array();

            $extension = array('jpeg','jpg','png','gif');
            $dir='upload';

            $bytes = 15284;
            $allowedKB = 15284;
            /* The Maths here is not correct if the max filesize is to be 100Kb - this is approx 222Mb!!! */
            #$totalBytes = $allowedKB * $bytes;
            /* 100Kb */
            $totalBytes = 102400;

            if( empty( $_FILES['files'] ) ) {
                echo '<b>Please, Select the files to upload!!!</b>';
                return;
            }


            /* create db connection  -- OO style here for simplicity */
            $conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

            /* use a prepared statement to help avoid sql injection attacks. */
            $query = 'insert into `uploads` ( `image_path`, `image_name` ) values (?,?)';

            $stmt = $conn->prepare( $query );
            if( !$stmt ) exit( sprintf( '<h1 style="color:red">Fatal error</h1>Unable to prepare sql query<br />%s [ code: %d ]', $conn->error, $conn->errno ) );

            /* bind placeholders in sql to variables to be populated later */
            $stmt->bind_param( 'ss', $dir, $name );


            /* iterate through the files */
            foreach( $_FILES['files']['name'] as $i => $name ) {

                if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {

                    $uploadThisFile = true;

                    $name = $_FILES['files']['name'][$i];
                    $size = $_FILES['files']['size'][$i];
                    $type = $_FILES['files']['type'][$i];
                    $tmp  = $_FILES['files']['tmp_name'][$i];
                    $error= $_FILES['files']['error'][$i];
                    $ext  = pathinfo( $name, PATHINFO_EXTENSION );
                    list( $width, $height, $type, $attr ) = getimagesize( $tmp );


                    if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){


                        $targetfile = __DIR__ . '/upload/' . $name;

                        if( !$width or !$height ){
                            $errors[]=sprintf('File %s is not an image', $name );
                            $uploadThisFile = false;
                        }

                        if( !in_array( strtolower( $ext ), $extension ) ){
                            $uploadThisFile = false;
                            $errors[]=sprintf('File type is invalid. Name:- %s', name );
                        }

                        if( $size > $totalBytes ){
                            $errors[]=sprintf('File size must be less than 100KB. Name:- %s',$name );
                            $uploadThisFile = false;
                        }

                        if( file_exists( $targetfile ) ){
                            $errors[]=sprintf('File already exists. Name:- %s', $name );
                            $uploadThisFile = false;
                            clearstatcache();
                        }

                        if( $uploadThisFile ){
                            /* insert record into db */
                            $status = move_uploaded_file( $tmp, $targetfile );

                            if( $status && $name && $dir ){
                                /* both $dir & $name are defined, execute query */
                                $result=$stmt->execute();
                                if( !$result ) $errors[]=sprintf('Problem storing %s to db - %s', $name, $stmt->error );
                                else $uploads[]=$name;
                            } else {
                                $errors[]=sprintf('Problem moving file %s to %s', $name, $targetfile );
                            }
                        }
                    } else {
                        $errors[]=sprintf( 'possible file upload attack - errorcode: %d', $error );
                    }
                }
            }//close foreach loop

            $stmt->close();
            $conn->close();
        }
    }
?>
<!doctype html>
<html>
    <head>
        <title>multiple file uploads</title>
    </head>
    <body>
        <form method='post' enctype='multipart/form-data'>
            <input type='hidden' name='sendimage' value='true' />
            <input type='file' name='files[]' multiple />
            <input type='submit' />


            <?php
                if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['sendimage'] ) ){
                    if( !empty( $errors ) ){
                        foreach( $errors as $error ) printf( '<br />%s', $error );
                    } else {
                        printf( '<br />No issues detected with uploads. %d files uploaded and stored in db', count( $uploads ) );
                    }
                }
            ?>
        </form>
    </body>
</html>