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.";
}

您应该考虑更改检查文件类型的方式,例如使用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)) {

干杯!!