Inspecting a csv file

I want to ensure an uploaded file is in th e correct format

<form action="upload_sites_engine.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" accept=".csv">
<input type="submit" value="Upload" name="submit">
</form>

and im using this to handle it

<?php
session_start();
  if($_SERVER["REQUEST_METHOD"] == "POST") {

    include 'db/pdo_conn.php'; 
    
`	$open = fopen($_FILES['fileToUpload']['tmp_name'], "r");

			while (($data = fgetcsv($open, 1000, ",")) !== false) {
				$array[] = $data;
			}

			fclose($open);

	if($array[0][0] != 'site_id') {
		
	  header("location: index.php?add_site_error");

	} else {

	  $handle = fopen($_FILES['fileToUpload']['tmp_name'],'r');
	  
	  $sql = "INSERT INTO sites 
	  (site_id,name,x_coord,y_coord
	  ) VALUES (
	  :site_id,:site_name,:site_x_coord,:site_y_coord
	  )";
	  
	  //echo $sql;
	  
	  $statement = $pdo->prepare($sql);

	fgetcsv($handle); // read and ignore header
	
	while($data = fgetcsv($handle))  {
		  

		  $statement->execute([
			':site_id' => $data[0],
			':site_name' => $data[1],
			':site_x_coord' => $data[2],
			':site_y_coord' => $data[3]
		   ]);

	  }

	fclose($handle);

	unset($_SESSION['success_message']);

	header("location: index.php?add_site_success");
	}
}
?>

Is it correct that I’m opening the fiile 2 times
Also, I want to confirm the format by checking the 1st element in the csv file is site_id, ok?
As it stands now, I gett

There’s a stray single quote at the beginning of this line - is it in the code?

No, what’s the point? You open the file and read it all into the $array array, so you already have all the file contents when you check the first element of the first row. Once you’re sure the data is OK, why not just iterate through $array (ignoring the first row of column names) instead of reading it all again? Or, just read the first row in for your check (so that the user knows quickly that the file isn’t correct), and then read the rest to process it.

// open the file
// read the first row
// if the first column of the first row isn't 'site_id', exit
// prepare the query
// loop:
//    read the next row
//    insert the data
//    until there is no more data
1 Like