Search code examples
phpupload

unable to upload file from multiple input in 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 directory
    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;
}
?>

Solution

  • 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 directory
        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;
    }
    ?>