如何在用户上载非.csv文件时添加错误消息

时间:2015-11-07 05:57:22

标签: php excel

我有一个用PHP上传.csv文件的代码。它运作正常。我想要的是,如果用户上传文档或图像类型,则显示警告或错误消息。这是我的代码:

<?php
   include_once 'db.php';
   if(isset($_POST['submit'])){

     if($_FILES['csv_data']['name']){
      $arrFileName = explode('.',$_FILES['csv_data']['name']);
      if($arrFileName[1] == 'csv'){
        $handle = fopen($_FILES['csv_data']['tmp_name'], "r");
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $item1 = mysqli_real_escape_string($dbConnection,$data[0]);
        $item2 = mysqli_real_escape_string($dbConnection,$data[1]);
        $import="INSERT into tbl_csv values('','$item1','$item2')";
        mysqli_query($dbConnection,$import);
      }
       fclose($handle);
        print "Import done";
     }
     }else{
     echo "only Excel";
     }
   }
?>


 <html>
 <head>
 <title>Upload CSV and Insert into Database Using PHP</title>
 <head>
 <body>
 <form method='POST' enctype='multipart/form-data'>
  Upload CSV: <input type='file' name='csv_data' /> <input type='submit' name='submit' value='import' />
 </form>
 </body>
 </html>

怎么做?

2 个答案:

答案 0 :(得分:1)

你可以使用

if(pathinfo( $_FILES['csv_data']['name'],PATHINFO_EXTENSION) =='csv')

if ($_FILES['csv_data']['type'] == 'text/csv')

这是你的php代码

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

            if (!empty($_FILES['csv_data']['name'])) {
                if(pathinfo( $_FILES['csv_data']['name'],PATHINFO_EXTENSION) =='csv') {
                    $handle = fopen($_FILES['csv_data']['tmp_name'], "r");
                    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        $item1 = mysqli_real_escape_string($dbConnection, $data[0]);
                        $item2 = mysqli_real_escape_string($dbConnection, $data[1]);
                        $import = "INSERT into tbl_csv values('','$item1','$item2')";
                        mysqli_query($dbConnection, $import);
                    }
                    fclose($handle);
                    print "Import done";
                }
                else{
                   echo "only csv file allowed"; 
                }
            } else {
                echo "Please select file";
            }
        }

答案 1 :(得分:0)

更新:

csv_file_upload.php:

<?php

   if(isset($_POST['submit'])){
        if(isset($_FILES['csv_data']['tmp_name'])){
            $file_ext = end( (explode('.',$_FILES['csv_data']['name']) ));
            if($file_ext == 'csv' || $file_ext == 'CSV'){
                echo 'CSV file uploaded!';
            }
            else { 
              echo 'ERROR: No CSV file uploaded!';
            }
        }
   }
?>


 <html>
 <head>
 <title>Upload CSV and Insert into Database Using PHP</title>
 <head>
 <body>
 <form method='POST' action="csv_file_upload.php" enctype='multipart/form-data'>
  Upload CSV: <input type='file' name='csv_data' /> <input type='submit' name='submit' value='import' />
 </form>
 </body>
 </html>