首页 > 解决方案 > 上传多张图片的脚本:第一张图片更改其他图片的扩展名

问题描述

我有这个脚本用于上传多张图片。如果我同时上传相同类型的图像,例如,所有 jpg、gif 或 png 它工作得很好,但如果我上传混合图像类型(混合 jpg、gif、png)到数据库我具有相同扩展名的所有图像。在 foreach 中,加载的第一个图像将扩展名更改为其他图像。这仅发生在数据库中,因为 class.upload.php 类将图像正确上传到文件夹中。

任何想法?谢谢

    if($_FILES){

try{


$files = array();
    foreach ($_FILES['group'] as $k => $l) {
        foreach ($l as $i => $v) {
            if (!array_key_exists($i, $files))
               $files[$i] = array();
                $files[$i][$k] = $v;
        }
    }

foreach ($files as $file) {

  $query = "INSERT INTO gallery (img, alt_image, created) VALUES (:image, :alt, :created)";  

// prepare query for execution
 $stmt = $con->prepare($query); 

        $name = $_FILES['group']['name'][0];
        $ext = pathinfo($name, PATHINFO_EXTENSION);
        $rand = md5(uniqid().rand());
        $post_image = $rand.".".strtolower($ext); 
        $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $post_image); 

  $handle = new upload($file); 
  if ($handle->uploaded) {

      $handle->file_new_name_body   =   strtolower($withoutExt);
      $handle->image_resize     = true;
      $handle->image_ratio_crop = true;
      $handle->image_x          = 720;
      $handle->image_y          = 630;


    $handle->process('../../images/gallery/'); 
    if ($handle->processed) {
         $handle->clean();
      } else {
      echo 'Error: ' . $handle->error; 
    } 

  } 
  unset($handle);


// bind the parameters
$stmt->bindParam(':image', $post_image);
$stmt->bindParam(':alt', $name);

$created=date('Y-m-d H:i:s'); // specify when this record was inserted to the database
$stmt->bindParam(':created', $created);
   // Execute the query
        if($stmt->execute()){
            echo "<div class='alert alert-success'>Success.</div>";

      }else{
            echo "<div class='alert alert-danger'>Error.</div>";
        }
   }
}

    // show error
    catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }
}
?>

标签: phpmysqlpdo

解决方案


您不应始终在$_FILES数组的第一个元素上构建文件扩展名,而应使用自己收集的$files内容:

$name = $file['name'];
$ext = pathinfo($name, PATHINFO_EXTENSION);

...此外,请查看一些调试教程。他们会帮助您自己发现该错误;)


推荐阅读