【问题标题】:Script for upload multi images: the first image change the extension of the others上传多张图片的脚本:第一张图片更改其他图片的扩展名
【发布时间】:2019-03-06 16:05:05
【问题描述】:

我有这个脚本用于上传多张图片。 如果我同时上传相同类型的图像,例如,所有 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());
    }
}
?>

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      相关资源
      最近更新 更多