文件上传并将数据插入php myadmin中时出错

时间:2019-05-16 05:48:57

标签: php

此代码出现错误。我想将文件上传内容限制为1.5 mb,类型仅是doc文件...首先提示警告,现在仅提示文件类型警报和数据,但也保存到php myadmin中。其中包括我不想要的所有类型的文件,例如pdf,mp4等。任何人都有解决方案。

此处提供代码:

<?php
$con = mysqli_connect("localhost","root","","physiocon");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$edit_state = false;

if(isset($_POST['submit'])) {

 $name = $_POST['name'];
 $email= $_POST['email'];
 $abscategory = $_POST['abscategory'];
 $submcategory = $_POST['submcategory'];
 $uploadOk = 1;

 $file = $_FILES['file']['name'];

 $target = "admin/submitted abstracts/".basename($_FILES['file'['name']);

  $imageFileType = strtolower(pathinfo($target,PATHINFO_EXTENSION));

    // Check if file already exists
 if (file_exists($target)) {
  echo ("<script LANGUAGE='JavaScript'>
  window.alert('Sorry File is already Exists. Please Upload Another File 
  or Rename Your File!');
  window.location.href='abstract_submission.php';
  </script>");
  $uploadOk = 0;
}

// Check file size
if ($_FILES["file"]["size"] > 1500) {
    echo ("<script LANGUAGE='JavaScript'>
  window.alert('Sorry File Size Allowed is upto 1.5 MB !');
  window.location.href='abstract_submission.php';
  </script>");
    $uploadOk = 0;
  }

    // Allow certain file formats
if($imageFileType != "doc") {
    echo ("<script LANGUAGE='JavaScript'>
  window.alert('Sorry only .doc file is allowed !');
  window.location.href='abstract_submission.php';
  </script>");
    $uploadOk = 0;
}

$sql="INSERT INTO `abstracts`(`name`, `email`, `abs_file`, `abs_ategory`, 
     `subm_category`) VALUES 
   ('$name','$email','$file','$abscategory','$submcategory')";

mysqli_query($con, $sql);

if (move_uploaded_file($_FILES['file']['tmp_name'], $target)){

 echo ("<script LANGUAGE='JavaScript'>
  window.alert('Testimonial Added Successfully !');
  window.location.href='abstract_submission.php';
  </script>");

} else {
  echo "Error updating record: " . mysqli_error($con); 
}
}

?>

2 个答案:

答案 0 :(得分:0)

好吧,您正在设置变量$ uploadOk,但是您从未检查过它。

如果该变量为0,请尝试停止执行。这样就不会进行SQL查询。

......
if($imageFileType != "doc") {
  echo ("<script LANGUAGE='JavaScript'>
  window.alert('Sorry only .doc file is allowed !');
  window.location.href='abstract_submission.php';
  </script>");
  $uploadOk = 0;
}
if ($uploadOk === 0) {
  die("Invalid upload");
}
.......

考虑对$ uploadOk变量使用布尔值(真或假),而不是整数。

此外,您的代码已打开以进行sql注入。不要在SQL语句中直接使用$ _POST值。

答案 1 :(得分:0)

您可以通过检查上传文件的扩展名(按名称)来验证文件类型。

替换下面的代码条件

  // Allow certain file formats
 if($imageFileType != "doc"){
    // Your JavaScript code
 }

用替换条件

$allowedExtsImg=array("doc","docx");
$extensionsub = explode(".", $file);
$extension = strtolower(end($extensionsub));
if (!in_array($extension, $allowedExtsImg))
{
  //Enter your JavaScript code here
}

在所有验证结束后,在代码编写条件之前

// This condition will prevent below action if there is a validation error above.
if($uploadOk!=0){
   // Your Insert Query, and Upload file Code
}