将图像上传到文件夹,并在php中插入数据库和文本文件的路径 [英] upload image to folder and insert path to database and text files in php

查看:128
本文介绍了将图像上传到文件夹,并在php中插入数据库和文本文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php
error_reporting( ~E_NOTICE );
require_once 'dbconfig.php';

if($_POST)
{
  $firstname = $_POST['firstname'];
  $lastname = $_POST['lastname'];
  $description = $_POST['description'];
  $election_name=$_POST['election_name'];
  $category_name=$_POST['category_name'];

  $imgFile = $_FILES['user_image']['name'];
  $tmp_dir = $_FILES['user_image']['tmp_name'];
  echo $imgSize = $_FILES['user_image']['size'];

  $upload_dir = 'user_images'; // upload directory

  $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

  // valid image extensions
  $valid_extensions = array('jpg', 'jpeg', 'png', 'gif'); // valid extensions

  // rename uploading image
  $photo = rand(1000,1000000).".".$imgExt;

  // allow valid image file formats
  if(in_array($valid_extensions,$imgExt)) {            

    // Check file size '5MB'
    if($imgSize > 5000000) { 
      move_uploaded_file($tmp_dir,"$upload_dir/$imgFile");
        try {

          $stmt = $db_con->prepare("INSERT INTO candidate(firstname,lastname,description,election_name,category_name,photo) VALUES(:ename, :edept, :esalary, :elect, :cat, :ima)");
          $stmt->bindParam(":ename", $firstname);
          $stmt->bindParam(":edept", $lastname);
          $stmt->bindParam(":esalary", $description);
          $stmt->bindParam(":elect", $election_name);
          $stmt->bindParam(":cat", $category_name);
          $stmt->bindParam(":ima", $photo);

          if($stmt->execute())
          {
              echo "Successfully Added";
          }
          else{
              echo "Query Problem";
          }   
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
    else{
        echo "Sorry, your file is too large.";
    }
  }
  else {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";     
  }
?>

我有此代码可以上传图像和文本文件,但它表示抱歉,只有JPG,JPEG,PNG和.允许使用GIF文件.我已经尝试解决了很多次,但是我自己找不到解决方案,请提出正确的解决方法.

I have this code to upload image and text files but it say Sorry, only JPG, JPEG, PNG & GIF files are allowed. I've tried to solve this many times but i can't find solution on my own, please suggest the correct way of doing this.

推荐答案

您需要更改

 if (in_array($valid_extensions, $imgExt)) {

收件人

 if (in_array($imgExt,$valid_extensions)) {

in_array 首先需要参数作为搜索值,第二个参数作为数组

in_array need first parameter as search value and second parameter as your array

您总是返回假值,并且得到了该错误

You always return false value and you got that error

这篇关于将图像上传到文件夹,并在php中插入数据库和文本文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆