文件上传文件类型和文件大小的php抛出错误,虽然它在定义的规则内

时间:2015-02-05 08:03:14

标签: php mysql file-upload

使用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."虽然它符合文件类型和文件大小。

2 个答案:

答案 0 :(得分:1)

您不会想要查找更多要检查的案例,您需要将它们分开。

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检查文件类型的方式,例如使用pathinfo

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

$extensions是您的预定义数组。

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

答案 1 :(得分:0)

而不是这一行

//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)) {

干杯!!