Skip to content

Instantly share code, notes, and snippets.

@encoderit-arman
Created March 2, 2022 10:12
Show Gist options
  • Save encoderit-arman/2ba8d8363ad520be6b53ee2a4e0912ac to your computer and use it in GitHub Desktop.
Save encoderit-arman/2ba8d8363ad520be6b53ee2a4e0912ac to your computer and use it in GitHub Desktop.
if (isset($_POST["data"])) {
// Get file extension
$file_extension = pathinfo($_FILES["data"]["name"], PATHINFO_EXTENSION);
// Validate file input to check if is not empty
if (!file_exists($_FILES["data"]["tmp_name"])) {
$response = array(
"type" => "error",
"message" => "File input should not be empty."
);
} // Validate file input to check if is with valid extension
else if ($file_extension != "csv") {
$response = array(
"type" => "error",
"message" => "Invalid CSV: File must have .csv extension."
);
echo '334343';
} // Validate file size
else if (($_FILES["data"]["size"] > 2000000)) {
$response = array(
"type" => "error",
"message" => "Invalid CSV: File size is too large."
);
} // Validate if all the records have same number of fields
else {
$lengthArray = array();
$row = 1;
if (($fp = fopen($_FILES["data"]["tmp_name"], "r")) !== FALSE) {
fgetcsv($fp, 1000, ",");
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$lengthArray[] = count($data);
}
fclose($fp);
}
$lengthArray = array_unique($lengthArray);
if (count($lengthArray) == 1) {
$response = array(
"type" => "success",
"message" => "File Validation Success."
);
} else {
$response = array(
"type" => "error",
"message" => "Invalid CSV: Count mismatch."
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment