php文件上传检查文件是否是图像

问题描述 投票:-1回答:1

我有一个用于图像上传的PHP脚本,但我需要一些代码来检查文件是否是图像。是的,我知道。已经多次询问过这个问题了。但是,我的文件输入是将数据作为数组发送,因此我无法使用其他人在其他线程上发送的代码来检查文件是否是图像。

这是我的html表单

<form action="functions/imgupload.php" method="post" enctype="multipart/form-data">
  <div class="form-group">
    <label for="imgtitle">Image Title:</label>
    <input type="text" class="form-control" name="imgtitle" id="imgtitle">
  </div>
  <div class="form-group">
    <label for="imgdesc">Image Description:</label>
    <input type="text" class="form-control" name="imgdesc" id="imgdesc">
  </div>
  <input type="file" name="img[]" id="fileToUpload" multiple>
  <input type="submit" value="Upload Image" name="submit">
</form>

这是我的PHP代码

<?php
include("../../config/config.php");
$img = $_FILES['img'];

if(!empty($img)) {
  $img_desc = reArrayFiles($img);

  foreach($img_desc as $val) {
    $newname = date('YmdHis',time()).mt_rand().'.jpg';
    $stmt = $conn->prepare("INSERT INTO gallery (imgsrc, title, description) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $newname, $_POST['imgtitle'], $_POST['imgdesc']);
    if($stmt->execute()) {
      move_uploaded_file($val['tmp_name'],'../../images/'.$newname);
      header("location: ../");
    }
  }
}

function reArrayFiles($file) {
  $file_ary = array();
  $file_count = count($file['name']);
  $file_key = array_keys($file);

  for($i=0;$i<$file_count;$i++) {
    foreach($file_key as $val) {
      $file_ary[$i][$val] = $file[$val][$i];
    }
  }

  return $file_ary;
}
php
1个回答
1
投票

可能它会帮助你,

if(!empty($_FILES['img'])) {
    $img = $_FILES['img'];

    foreach($img['name'] as $key => $name) {
        $type = $img['type'][ $key ];
        $type = strtolower($type);
        if($type == 'image/jpg' || $type == 'image/jpeg' || $type == 'image/png' || $type == 'image/gif'){
            $newname = date('YmdHis',time()).mt_rand().'.jpg';
            $stmt = $conn->prepare("INSERT INTO gallery (imgsrc, title, description) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $newname, $_POST['imgtitle'], $_POST['imgdesc']);
            if($stmt->execute()) {
                move_uploaded_file($img['tmp_name'][ $key ],'../../images/'.$newname);
            }
        }
    }

    header("location: ../");
}
© www.soinside.com 2019 - 2024. All rights reserved.