Uploading and Validating CSV Files in PHP: Extracting Data Safely and Efficiently

To upload a CSV file with validation and extract its data using PHP, you can follow these steps:

  1. Create a HTML form that allows the user to select the CSV file to upload:
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select CSV file to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload CSV" name="submit">
</form>
  1. In the PHP script that handles the form submission (upload.php in this example), check that the file was uploaded successfully and is a CSV file:
if (isset($_POST["submit"])) {
  $target_dir = "uploads/";
  $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
  $uploadOk = 1;
  $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  // Check if file is a CSV file
  if($fileType != "csv") {
    echo "Only CSV files are allowed.";
    $uploadOk = 0;
  }

  // Check if file was uploaded successfully
  if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
  } else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
      echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
    } else {
      echo "Sorry, there was an error uploading your file.";
    }
  }
}
  1. If the file was uploaded successfully and is a CSV file, validate the contents of the file to ensure that it contains the expected data. For example, you could check that the first row of the file contains the expected column names:
if ($uploadOk == 1 && $fileType == "csv") {
  $file = fopen($target_file, "r");

  // Check that first row contains expected column names
  $expected_columns = ["Name", "Email", "Phone"];
  $actual_columns = fgetcsv($file);
  if ($actual_columns !== $expected_columns) {
    echo "The CSV file must have the following columns: " . implode(", ", $expected_columns);
    fclose($file);
    unlink($target_file); // Delete the file
    exit;
  }

  // Process the rest of the rows
  echo "<table>";
  while (($data = fgetcsv($file)) !== FALSE) {
    echo "<tr>";
    foreach ($data as $value) {
      echo "<td>" . $value . "</td>";
    }
    echo "</tr>";
  }
  echo "</table>";
  fclose($file);
}

This code checks that the first row of the CSV file contains the expected column names (“Name”, “Email”, “Phone”). If the column names are not as expected, it displays an error message and deletes the uploaded file using unlink(). If the column names are correct, it processes the rest of the rows using fgetcsv() and displays them as an HTML table.