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

时间:2019-03-08 13:22:56

标签: php

我有一个用于上传图片的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;
}

1 个答案:

答案 0 :(得分: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: ../");
}
相关问题