dongluanban3536 2018-05-18 09:25
浏览 49
已采纳

无法从PHP中的多个输入上传文件

Am using below code to upload file from multiple input and create thumbnail for uploaded image and file rename, but am unable to upload image.

Can someone correct me where i made mistake

Note: For some reason i dont want to change HTML file input i need 4 input.

CODE

<form role="form" method="post" action="" enctype="multipart/form-data" autocomplete="on">
<input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
<input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
<input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
<input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
</form>


    <?php
require('includes/config.php');

if (!empty($_POST)) {
    $newname = md5(rand() * time());
    if (isset($_FILES['files'])) {
        $uploadedFiles = array();
        foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
            $errors = array();
            $file_name = md5(uniqid("") . time());
            $file_size = $_FILES['files']['size'][$key];
            $file_tmp = $_FILES['files']['tmp_name'][$key];
            $file_type = $_FILES['files']['type'][$key];

            if ($file_type == "image/gif") {
                $sExt = ".gif";
            } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
                $sExt = ".jpg";
            } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
                $sExt = ".png";
            }
            if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
                $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
            }
            if ($file_size > 2097152000) {
                $errors[] = 'File size must be less than 2 MB';
            }
            $desired_dir = "upload/";
            if (empty($errors)) {
                if (is_dir($desired_dir) == false) {
                    mkdir("$desired_dir", 0700);        // Create directory if it does not exist
                }
                if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
                    $uploadedFiles[$key] = array($file_name . $sExt, 1);
                } else {
                    echo "Couldn't upload file " . $_FILES['files']['name'][$key];
                    $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
                }
            } else {

            }
        }

        foreach ($uploadedFiles as $key => $row) {
            if (!empty($row[1])) {
                $codestr = '$file' . ($key + 1) . ' = $row[0];';
                eval($codestr);
            } else {
                $codestr = '$file' . ($key + 1) . ' = NULL;';
                eval($codestr);
            }
        }
    }
    $orig_directory = "$desired_dir";    //Full image folder
    $thumb_directory = "thumb/";    //Thumbnail folder

    /* Opening the thumbnail directory and looping through all the thumbs: */
    $dir_handle = opendir($orig_directory); //Open Full image dirrectory
    if ($dir_handle > 1) { //Check to make sure the folder opened
        $allowed_types = array('jpg', 'jpeg', 'gif', 'png');
        $file_type = array();
        $ext = '';
        $title = '';
        $i = 0;

        while ($file_name = readdir($dir_handle)) {
            /* Skipping the system files: */
            if ($file_name == '.' || $file_name == '..') {
                continue;
            }

            $file_type = \explode('.', $file_name);    //This gets the file name of the images
            $ext = strtolower(array_pop($file_type));

            /* Using the file name (withouth the extension) as a image title: */
            $title = implode('.', $file_type);
            $title = htmlspecialchars($title);

            /* If the file extension is allowed: */
            if (in_array($ext, $allowed_types)) {

                /* If you would like to inpute images into a database, do your mysql query here */

                /* The code past here is the code at the start of the tutorial */
                /* Outputting each image: */

                $nw = 100;
                $nh = 100;
                $source = "$desired_dir{$file_name}";
                $stype = explode(".", $source);
                $stype = $stype[count($stype) - 1];
                $dest = "thumb/{$file_name}";

                $size = getimagesize($source);
                $w = $size[0];
                $h = $size[1];

                switch ($stype) {
                    case 'gif':
                        $simg = imagecreatefromgif($source);
                        break;
                    case 'jpg':
                        $simg = imagecreatefromjpeg($source);
                        break;
                    case 'png':
                        $simg = imagecreatefrompng($source);
                        break;
                }

                $dimg = resizePreservingAspectRatio($simg, $nw, $nh);
                imagepng($dimg, $dest);



            }
        }

        /* Closing the directory */
        closedir($dir_handle);
    }

    $stmt = $db->prepare('INSERT INTO car (title, brand, model, kmdriven, price, nego, year, addes, sname, smail, sphone) VALUES (:title, :brand, :model, :kmdriven, :price, :nego, :year, :addes, :sname, :smail, :sphone)');
    $stmt->execute(array(
        ':title' => filter_input(INPUT_POST, 'title'),
        ':brand' => filter_input(INPUT_POST, 'brand'),
        ':model' => filter_input(INPUT_POST, 'model'),
        ':kmdriven' => filter_input(INPUT_POST, 'kmdriven'),
        ':price' => filter_input(INPUT_POST, 'price'),
        ':nego' => filter_input(INPUT_POST, 'nego'),
        ':year' => filter_input(INPUT_POST, 'year'),
        ':addes' => filter_input(INPUT_POST, 'addes'),
        ':sname' => filter_input(INPUT_POST, 'sname'),
        ':smail' => filter_input(INPUT_POST, 'smail'),
        ':sphone' => filter_input(INPUT_POST, 'sphone')
    ));
 function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
                    $srcWidth = imagesx($img);
                    $srcHeight = imagesy($img);

                    // Determine new width / height preserving aspect ratio
                    $srcRatio = $srcWidth / $srcHeight;
                    $targetRatio = $targetWidth / $targetHeight;
                    if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
                        $imgTargetWidth = $srcWidth;
                        $imgTargetHeight = $srcHeight;
                    } else if ($targetRatio > $srcRatio) {
                        $imgTargetWidth = (int) ($targetHeight * $srcRatio);
                        $imgTargetHeight = $targetHeight;
                    } else {
                        $imgTargetWidth = $targetWidth;
                        $imgTargetHeight = (int) ($targetWidth / $srcRatio);
                    }

                    // Creating new image with desired size
                    $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);

                    // Add transparency if your reduced image does not fit with the new size
                    $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
                    imagefill($targetImg, 0, 0, $targetTransparent);
                    imagecolortransparent($targetImg, $targetTransparent);

                    // Copies image, centered to the new one (if it does not fit to it)
                    imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

                    return $targetImg;
                }
    header('Location: index.php');
    exit;
}
?>
  • 写回答

1条回答 默认 最新

  • dongqiangou5724 2018-05-18 09:29
    关注

    When you are writing client-side code, all you need to know is use enctype="multipart/form-data" when your form includes any <input type="file"> elements.

    <form role="form" method="post" action="" enctype="multipart/form-data" autocomplete="on">
    <input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
    <input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
    <input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
    <input type="file" name="files[]" id="upload-image-three" onchange="readURL(this);">
    </form>
    
    
    <?php
    require('includes/config.php');
    
    if (!empty($_POST)) {
        $newname = md5(rand() * time());
        if (isset($_FILES['files'])) {
            $uploadedFiles = array();
            foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
                $errors = array();
                $file_name = md5(uniqid("") . time());
                $file_size = $_FILES['files']['size'][$key];
                $file_tmp = $_FILES['files']['tmp_name'][$key];
                $file_type = $_FILES['files']['type'][$key];
    
                if ($file_type == "image/gif") {
                    $sExt = ".gif";
                } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
                    $sExt = ".jpg";
                } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
                    $sExt = ".png";
                }
                if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
                    $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
                }
                if ($file_size > 2097152000) {
                    $errors[] = 'File size must be less than 2 MB';
                }
                $desired_dir = "upload/";
                if (empty($errors)) {
                    if (is_dir($desired_dir) == false) {
                        mkdir("$desired_dir", 0700);        // Create directory if it does not exist
                    }
                    if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
                        $uploadedFiles[$key] = array($file_name . $sExt, 1);
                    } else {
                        echo "Couldn't upload file " . $_FILES['files']['name'][$key];
                        $uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
                    }
                } else {
    
                }
            }
    
            foreach ($uploadedFiles as $key => $row) {
                if (!empty($row[1])) {
                    $codestr = '$file' . ($key + 1) . ' = $row[0];';
                    eval($codestr);
                } else {
                    $codestr = '$file' . ($key + 1) . ' = NULL;';
                    eval($codestr);
                }
            }
        }
        $orig_directory = "$desired_dir";    //Full image folder
        $thumb_directory = "thumb/";    //Thumbnail folder
    
        /* Opening the thumbnail directory and looping through all the thumbs: */
        $dir_handle = opendir($orig_directory); //Open Full image dirrectory
        if ($dir_handle > 1) { //Check to make sure the folder opened
            $allowed_types = array('jpg', 'jpeg', 'gif', 'png');
            $file_type = array();
            $ext = '';
            $title = '';
            $i = 0;
    
            while ($file_name = readdir($dir_handle)) {
                /* Skipping the system files: */
                if ($file_name == '.' || $file_name == '..') {
                    continue;
                }
    
                $file_type = \explode('.', $file_name);    //This gets the file name of the images
                $ext = strtolower(array_pop($file_type));
    
                /* Using the file name (withouth the extension) as a image title: */
                $title = implode('.', $file_type);
                $title = htmlspecialchars($title);
    
                /* If the file extension is allowed: */
                if (in_array($ext, $allowed_types)) {
    
                    /* If you would like to inpute images into a database, do your mysql query here */
    
                    /* The code past here is the code at the start of the tutorial */
                    /* Outputting each image: */
    
                    $nw = 100;
                    $nh = 100;
                    $source = "$desired_dir{$file_name}";
                    $stype = explode(".", $source);
                    $stype = $stype[count($stype) - 1];
                    $dest = "thumb/{$file_name}";
    
                    $size = getimagesize($source);
                    $w = $size[0];
                    $h = $size[1];
    
                    switch ($stype) {
                        case 'gif':
                            $simg = imagecreatefromgif($source);
                            break;
                        case 'jpg':
                            $simg = imagecreatefromjpeg($source);
                            break;
                        case 'png':
                            $simg = imagecreatefrompng($source);
                            break;
                    }
    
                    $dimg = resizePreservingAspectRatio($simg, $nw, $nh);
                    imagepng($dimg, $dest);
    
    
    
                }
            }
    
            /* Closing the directory */
            closedir($dir_handle);
        }
    
        $stmt = $db->prepare('INSERT INTO car (title, brand, model, kmdriven, price, nego, year, addes, sname, smail, sphone) VALUES (:title, :brand, :model, :kmdriven, :price, :nego, :year, :addes, :sname, :smail, :sphone)');
        $stmt->execute(array(
            ':title' => filter_input(INPUT_POST, 'title'),
            ':brand' => filter_input(INPUT_POST, 'brand'),
            ':model' => filter_input(INPUT_POST, 'model'),
            ':kmdriven' => filter_input(INPUT_POST, 'kmdriven'),
            ':price' => filter_input(INPUT_POST, 'price'),
            ':nego' => filter_input(INPUT_POST, 'nego'),
            ':year' => filter_input(INPUT_POST, 'year'),
            ':addes' => filter_input(INPUT_POST, 'addes'),
            ':sname' => filter_input(INPUT_POST, 'sname'),
            ':smail' => filter_input(INPUT_POST, 'smail'),
            ':sphone' => filter_input(INPUT_POST, 'sphone')
        ));
    
        header('Location: index.php');
        exit;
    }
    
    function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
        $srcWidth = imagesx($img);
        $srcHeight = imagesy($img);
    
        // Determine new width / height preserving aspect ratio
        $srcRatio = $srcWidth / $srcHeight;
        $targetRatio = $targetWidth / $targetHeight;
        if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
            $imgTargetWidth = $srcWidth;
            $imgTargetHeight = $srcHeight;
        } else if ($targetRatio > $srcRatio) {
            $imgTargetWidth = (int) ($targetHeight * $srcRatio);
            $imgTargetHeight = $targetHeight;
        } else {
            $imgTargetWidth = $targetWidth;
            $imgTargetHeight = (int) ($targetWidth / $srcRatio);
        }
    
        // Creating new image with desired size
        $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
    
        // Add transparency if your reduced image does not fit with the new size
        $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
        imagefill($targetImg, 0, 0, $targetTransparent);
        imagecolortransparent($targetImg, $targetTransparent);
    
        // Copies image, centered to the new one (if it does not fit to it)
        imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
    
        return $targetImg;
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)