代码之家  ›  专栏  ›  技术社区  ›  sanoj lawrence

文件名保存为空到数据库

  •  -1
  • sanoj lawrence  · 技术社区  · 6 年前

    我使用以下代码将多个文件名上载、重命名和保存到数据库表中。

    菲律宾比索:

       require('../includes/config.php');
    $apdtitle = htmlspecialchars(trim(filter_input(INPUT_POST, 'apdtitle')));
    $apdcategory = 'Education';
    $apdsubcategory = 'Books';
    $pnumber = htmlspecialchars(trim(filter_input(INPUT_POST, 'pnumber')));
    $prodprice = htmlspecialchars(trim(filter_input(INPUT_POST, 'prodprice')));
    $apddescription = htmlspecialchars(trim(filter_input(INPUT_POST, 'apddescription')));
    $location = htmlspecialchars(trim(filter_input(INPUT_POST, 'pstloct')));
    $view = '1';
    $added_on = date('d-M-y');
    $status = 'active';
    $username ='sanoj';
    if (!empty($_POST)) {
        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/";
                $d = compress($file_tmp, "$desired_dir/" . $file_name . $sExt, 60);
                if (empty($errors)) {
                    if (is_dir($desired_dir) == false) {
                        mkdir("$desired_dir", 0700);
                    }
                    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";
        $thumb_directory = "../upload/thumb/";
        $dir_handle = opendir($orig_directory);
        if ($dir_handle > 1) {
            $allowed_types = array('jpg', 'jpeg', 'gif', 'png');
            $file_type = array();
            $ext = '';
            $title = '';
            $i = 0;
            while ($file_name = readdir($dir_handle)) {
                if ($file_name == '.' || $file_name == '..') {
                    continue;
                }
                $file_type = \explode('.', $file_name);
                $ext = strtolower(array_pop($file_type));
                $title1 = implode('.', $file_type);
                $title = htmlspecialchars($title1);
                if (in_array($ext, $allowed_types)) {
                    $nw = 250;
                    $nh = 180;
                    $source = "$desired_dir{$file_name}";
                    $stype1 = explode(".", $source);
                    $stype = $stype1[count($stype1) - 1];
                    $dest = "../upload/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);
                }
            }closedir($dir_handle);
        }
        $stmt = $db->prepare("INSERT INTO allpostdata(apdtitle, apdcategory, apdsubcategory, posted, usernme, view, location, pnumber, prodprice, apddescription, img1, img2, img3, img4, status)"
                . " VALUES (:apdtitle, :apdcategory, :apdsubcategory, :posted, :usernme, :view, :location, :pnumber, :prodprice, :apddescription, :img1, :img2, :img3, :img4, :status)");
        $stmt->bindParam(':apdtitle', $apdtitle, PDO::PARAM_STR, 100);
        $stmt->bindParam(':apdcategory', $apdcategory, PDO::PARAM_STR, 100);
        $stmt->bindParam(':apdsubcategory', $apdsubcategory, PDO::PARAM_STR, 100);
        $stmt->bindParam(':posted', $added_on, PDO::PARAM_STR, 100);
        $stmt->bindParam(':usernme', $username, PDO::PARAM_STR, 100);
        $stmt->bindParam(':view', $view, PDO::PARAM_STR, 100);
        $stmt->bindParam(':location', $location, PDO::PARAM_STR, 100);
        $stmt->bindParam(':pnumber', $pnumber, PDO::PARAM_STR, 100);
        $stmt->bindParam(':prodprice', $prodprice, PDO::PARAM_STR, 100);
        $stmt->bindParam(':apddescription', $apddescription, PDO::PARAM_STR, 100);
        $stmt->bindParam(':status', $status, PDO::PARAM_STR, 6);
        $stmt->bindParam(':img1', $file1);
        $stmt->bindParam(':img2', $file2);
        $stmt->bindParam(':img3', $file3);
        $stmt->bindParam(':img4', $file4);
        if ($stmt->execute()) {
            header('Location: ../../index.php');
        }exit;
    }
    
    function compress($source, $destination, $quality) {
        $info = getimagesize($source);
        if ($info['mime'] == 'image/jpeg') {
            $image = imagecreatefromjpeg($source);
        } elseif ($info['mime'] == 'image/gif') {
            $image = imagecreatefromgif($source);
        } elseif ($info['mime'] == 'image/png') {
            $image = imagecreatefrompng($source);
        }
        imagejpeg($image, $destination, $quality);
        return $destination;
    }
    
    function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
        $srcWidth = imagesx($img);
        $srcHeight = imagesy($img);
        $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);
        }
        $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
        $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
        imagefill($targetImg, 0, 0, $targetTransparent);
        imagecolortransparent($targetImg, $targetTransparent);
        imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
        return $targetImg;
    }
    

    所有其他输入都被正确地保存到数据库表中,但上载的图像名称没有被保存。它们被保存为空值。

    有人能把密码里的问题弄清楚吗?

    压缩

    function compress($source, $destination, $quality) {
        $info = getimagesize($source);
        if ($info['mime'] == 'image/jpeg') {
            $image = imagecreatefromjpeg($source);
        } elseif ($info['mime'] == 'image/gif') {
            $image = imagecreatefromgif($source);
        } elseif ($info['mime'] == 'image/png') {
            $image = imagecreatefrompng($source);
        }
        imagejpeg($image, $destination, $quality);
        return $destination;
    }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   sanoj lawrence    6 年前

    最后找到解决方案,/下面的代码可以上传文件名并保存到数据库中,还可以压缩上传的图片。

    代码

    if (!empty($_POST)) {
        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);
                    }
                    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']['tmp_name'][$key];
                        $uploadedFiles[$key] = array($_FILES['files']['tmp_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";
        $thumb_directory = "../upload/thumb/";
        $dir_handle = opendir($orig_directory);
        if ($dir_handle > 1) {
            $allowed_types = array('jpg', 'jpeg', 'gif', 'png');
            $file_type = array();
            $ext = '';
            $title = '';
            $i = 0;
            while ($file_name = readdir($dir_handle)) {
                if ($file_name == '.' || $file_name == '..') {
                    continue;
                }
                $file_type = \explode('.', $file_name);
                $ext = strtolower(array_pop($file_type));
                $title1 = implode('.', $file_type);
                $title = htmlspecialchars($title1);
                if (in_array($ext, $allowed_types)) {
                    $nw = 250;
                    $nh = 180;
                    $source = "$desired_dir{$file_name}";
                    $stype1 = explode(".", $source);
                    $stype = $stype1[count($stype1) - 1];
                    $dest = "../upload/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);
                    compress($source, "$desired_dir/" . $file_name, 50);
                }
            }closedir($dir_handle);
        }
        $stmt = $db->prepare("INSERT INTO allpostdata(apdtitle, apdcategory, apdsubcategory, brand, model, posted, usernme, view, location, pnumber, prodprice, apddescription, img1, img2, img3, img4, status)"
                . " VALUES (:apdtitle, :apdcategory, :apdsubcategory, :brand, :model, :posted, :usernme, :view, :location, :pnumber, :prodprice, :apddescription, :img1, :img2, :img3, :img4, :status)");
        $stmt->bindParam(':apdtitle', $apdtitle, PDO::PARAM_STR, 100);
        $stmt->bindParam(':apdcategory', $apdcategory, PDO::PARAM_STR, 100);
        $stmt->bindParam(':apdsubcategory', $apdsubcategory, PDO::PARAM_STR, 100);
        $stmt->bindParam(':brand', $pstbrnd, PDO::PARAM_STR, 100);
        $stmt->bindParam(':model', $pstmdl, PDO::PARAM_STR, 100);
        $stmt->bindParam(':posted', $added_on, PDO::PARAM_STR, 100);
        $stmt->bindParam(':usernme', $username, PDO::PARAM_STR, 100);
        $stmt->bindParam(':view', $view, PDO::PARAM_STR, 100);
        $stmt->bindParam(':location', $location, PDO::PARAM_STR, 100);
        $stmt->bindParam(':pnumber', $pnumber, PDO::PARAM_STR, 100);
        $stmt->bindParam(':prodprice', $prodprice, PDO::PARAM_STR, 100);
        $stmt->bindParam(':apddescription', $apddescription, PDO::PARAM_STR, 100);
        $stmt->bindParam(':status', $status, PDO::PARAM_STR, 6);
        $stmt->bindParam(':img1', $file1);
        $stmt->bindParam(':img2', $file2);
        $stmt->bindParam(':img3', $file3);
        $stmt->bindParam(':img4', $file4);
        if ($stmt->execute()) {
            header('Location: index.php');
        }exit;
    }
    
    function compress($source, $destination, $quality) {
        $info = getimagesize($source);
        if ($info['mime'] == 'image/jpeg') {
            $image = imagecreatefromjpeg($source);
        } elseif ($info['mime'] == 'image/gif') {
            $image = imagecreatefromgif($source);
        } elseif ($info['mime'] == 'image/png') {
            $image = imagecreatefrompng($source);
        }
        imagejpeg($image, $destination, $quality);
        return $destination;
    }
    
    function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
        $srcWidth = imagesx($img);
        $srcHeight = imagesy($img);
        $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);
        }
        $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
        $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
        imagefill($targetImg, 0, 0, $targetTransparent);
        imagecolortransparent($targetImg, $targetTransparent);
        imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
        return $targetImg;
    }
    
        2
  •  0
  •   Ravi Maniyar    6 年前

    根据评论中的讨论,您肯定需要从 move_uploaded_file() 这将满足您将图像名称保存到数据库中的第一个需要。

    关于优化图像,您可以使用 this Git集线器库。它使用命令行工具,如 JpegOptim PngQuant 这可以帮助您生成图像的无损优化。这将减少图像的大小,而不会失去质量。你的两个目的都会解决的。