php 中的文件上传在定义的规则范围内抛出文件类型和文件大小错误

File upload in php throwing error for file type and file size though its within the defined rules

我在使用 php 将文件上传到 mysql 时遇到问题。该脚本几乎适用于所有人,但它不适用于几台机器并抛出我为文件类型和文件大小设置的错误。

<?php 
include ('config.php');
error_reporting(E_ALL);
session_start();
ini_set('max_execution_time', 300);  //300 sec =5min

//csv file type check
$csv_mimetypes = array(
'text/csv',    
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',    
);
$msg="";
$maxsize    = 2097152;

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

//Validate if csv file type as specified in array and check file size must not exceed 2MB
  if ((in_array($_FILES['filename']['type'], $csv_mimetypes)) && ($_FILES['filename']['size'] < $maxsize)){

       if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] . "</h1>";
        }

     $csv_file=$_FILES['filename']['tmp_name'];
     $handle = fopen($csv_file, "r");

     $i=0;
     while (($data = fgetcsv($handle)) !== FALSE) {
        if($i>0){
          $import=mysql_query("insert statement");
        }
          $i=1;  
      }      
   $msg="Uploaded Successfully";   
  } else {
$msg="Something went wrong . Please check the file type and FileSize.";   
  }
 }
?>

这个上传文件的脚本 运行 很好,但是在上传时从几台机器上抛出错误 "Something went wrong . Please check the file type and FileSize." 尽管它符合文件类型和文件大小。

你不应该找到更多的案例来检查,你需要将它们分开。

if(in_array($_FILES['filename']['type'], $csv_mimetypes)) && ($_FILES['filename']['size'] < $maxsize)
{
    // Success, yay for me!
}
else
{
    // You have no idea what went wrong.
}

分离逻辑,即

$validType = in_array($_FILES['filename']['type'], $csv_mimetypes);
$validSize = $_FILES['filename']['size'] < $maxsize;

现在您可以具体检查哪里出了问题。

if(!$validType)
{
    $msg .= "The type is invalid.";
}
if(!$validSize)
{
    $msg .= "The size is invalid.";
}

你应该考虑 changing the way you check for the file's type, e.g. using pathinfo:

$ext = pathinfo($filename, PATHINFO_EXTENSION);
$validType = in_array($ext, $extensions);

其中 $extensions 是您预定义的数组。

无论出现什么问题,都必须将错误处理逻辑分开。

代替这一行

//Validate if csv file type as specified in array and check file size must not exceed 2MB
if ((in_array($_FILES['filename']['type'], $csv_mimetypes)) && ($_FILES['filename']['size'] < $maxsize)){

更改为:-

$type = explode('.',$_FILES['filename']['name']);
if((strtolower(end($type)) == 'csv') && ($_FILES['filename']['size']< $maxsize)) {

干杯!!