I have a script with the code below that inserts a .csv file into a table, and had an issue where if no file is selected, it throws "fgetcsv() expects parameter 1 to be resource, boolean given" about 1,000,000 times or so until it fills up the table, the error log, and eventually the server hard drive. I'm guessing someone probably has a simple solution on the below code on how to prevent that going forward, but I've just spent some time looking into it and haven't been able to find the solution.

<?php

$conn = mysql_connect("localhost", "dbuser", "dbpassword") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

// Delete existing values in test table before inserting updated file

$sql_ini = "TRUNCATE table";
      mysql_query($sql_ini) or die(mysql_error());

if(isset($_POST['SUBMIT']))
{
	$file = $_FILES['file']['tmp_name'];

$handle = fopen($file,"r");

while(($fileop = fgetcsv($handle,1000,",")) != false)
{
	$field1 = $fileop[0];
	$field2 = $fileop[1];
	$field3 = $fileop[2];

	// check for default values and delete locked row before inserting data

	if (!empty($field1))
	{
	// Insert .csv file into database

$sql = "INSERT INTO table (field1, field2, field3) values ('$field1', '$field2', '$field3')";
 mysql_query($sql) or die(mysql_error());
	 }
}
 if($sql)
   	{ 
	   	// Show whether or not the file was added successfully:

   echo "CSV file successfully imported.";

} else {

	echo "Data Insert Failed";
}
} 

}

?>


<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
    <input type="file" name="file" />
    <br>
    <br>
    <input type="submit" name="SUBMIT" value="Submit" />
</form>

Thank you in advance for your assistance, and I appreciate your help. 🙂

    Sure: check that [font=monospace]$file[/font] isn't empty before trying to open it. PHP even has a function to check whether a named file exists.

      Weedpacket;11006040 wrote:

      Sure: check that [font=monospace]$file[/font] isn't empty before trying to open it. PHP even has a function to check whether a named file exists.

      It looks like I need an if statement in front of the "handle" line and wrap it around the loop. Do you think adding this should solve it?

      if ($handle = fopen($file,"r")) {
        // while loop in here
      }
      
        Write a Reply...