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:
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)){
$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);
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;
$createdDate = date('Y-m-d H:i:s');
$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."');";
s
if($duplicateList=="")
{
$insertTable= mysql_query($query);
}
else { $duplicatedRows .= "<li>Row ".$rowCount. $duplicateList ."</li>"; }
}
if ($duplicatedRows <> ""){
echo "<br/>Item rows that has not been uploaded. <ul> ".$duplicatedRows . "</ul>";
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.