Click here to Skip to main content
15,883,921 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!
How do I validate excel file(.xls and .xlsx)?

I have an upload function in my PHP code but I do not have a way to validate if excel file is .xls or .xlsx.

Here is the sample code:

PHP
if(isset($_POST['Submit'])){
    $duplicatedRows = "";
    $mimes = array('application/vnd.ms-excel','text/xls','text/xlsx');

    set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
    include 'PHPExcel/IOFactory.php';

    if(in_array($_FILES["csv"]["type"],$mimes)){
        // This is the file path to be uploaded.
        $inputFileName = $_FILES["csv"]["tmp_name"];

        try {
            $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        } catch(Exception $e) {
            die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
        }


        $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
        $arrayCount = count($allDataInSheet);  // Here get total count of row in that Excel sheet


        for($i=2;$i<=$arrayCount;$i++){
            $item = trim($allDataInSheet[$i]["A"]);
            $category = trim($allDataInSheet[$i]["B"]);
            $model = trim($allDataInSheet[$i]["C"]);
            $serialnum = trim($allDataInSheet[$i]["D"]);
            $description = trim($allDataInSheet[$i]["E"]);
            $barcode = trim($allDataInSheet[$i]["F"]);
            $satellite = trim($allDataInSheet[$i]["G"]);
            $location = trim($allDataInSheet[$i]["H"]);
            $remarks = trim($allDataInSheet[$i]["I"]);
            $department = trim($allDataInSheet[$i]["J"]);
            $supplier = trim($allDataInSheet[$i]["K"]);
            $accntble = trim($allDataInSheet[$i]["L"]);
            $cost = trim($allDataInSheet[$i]["M"]);
            $lifespan = trim($allDataInSheet[$i]["N"]);
            $movable = trim($allDataInSheet[$i]["O"]);
            $datepurchased = trim($allDataInSheet[$i]["P"]);

            $result = mysql_query("select * from tblItem");
            $count = mysql_num_rows($result);
            $dateToday = date("ymd");
            $itemNum = $dateToday.$count;

            //get date today for CreatedDate
            $createdDate = date('Y-m-d H:i:s');

            //check if their is duplicate in Serial Number and Barcode. It also check if date is valid.
            $duplicateList = checkFields($serialnum, $barcode);


            $query = "INSERT INTO `tblitem`(`ItemID`, `Item`, `Category`, `Model`, `SerialNum`, `Description`, `Barcode`, `Satellite`
            , `Location`, `Remarks`, `Supplier`, `Department`, `Accntble`, `Cost`, `LifeSpan`, `Movable`
            , `DatePurchased`, `CreatedBy`, `CreatedDate`) VALUES
            ('".$itemNum."','".$item."','".$category."','".$model."','".$serialnum."','".$description."','".$barcode."','".$satellite."','".$location."'
            ,'".$remarks."','".$supplier."','".$department."','".$accntble."','".$cost."'
            ,'".$lifespan."','".$movable."','".$datepurchased."','20140','".$dateToday."');";
            //$sql = mysql_query($query);
            //$recResult = mysql_fetch_array($sql);
        s
            if($duplicateList=="")
            {
                $insertTable= mysql_query($query);

                //$msg = 'Records has been added.';
            }
            else { $duplicatedRows .= "<li>Row ".$rowCount. $duplicateList ."</li>"; }
        }
        //echo "<div style='font: bold 18px arial,verdana;padding: 45px 0 0 500px;'>".$msg."</div>";

        if ($duplicatedRows <> ""){
            //echo $duplicateList."<br/>";
            echo "<br/>Item rows that has not been uploaded. <ul> ".$duplicatedRows . "</ul>";//list of duplicate not uploaded.
            echo "Some items are already uploaded. [".$arrayCount." Items]";
        }
        else{ echo "All items from CSV are already uploaded. [".$arrayCount." Items]"; }
    } else { die("<br/>Sorry, File type is not allowed. Only Excel file."); }
}


I have this validator but it is not working properly because when I try to upload a .csv file, it accepts it which causes error in my codes.

Thank you for the help.
Posted
Comments
[no name] 20-Mar-15 0:54am    
Better ;-)
Michelle Anne Rigor 20-Mar-15 1:04am    
Okay thanks.

What @Gocoolprasad meant was:

PHP
//$filename = $_POST['your_field_file'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);


$filename = "/home/user1/whatever.xls"; //or $_POST['your_field_file'];
echo $finfo->file($filename);


You can check this link for reference.
 
Share this answer
 
PHP
$filename = "/home/user1/whatever.xls"; //or $_POST['your_field_file'];
echo $finfo->file($filename);
 
Share this answer
 
Comments
Michelle Anne Rigor 20-Mar-15 21:10pm    
What is the finfo variable?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900