I am a PHP beginner writing a program to upload .csv files to a webpage. When testing my program, I have been using a file called Partitions.csv. However, now I need to upload files that are named differently and when I try to do this, my code will not accept the file. This is my HTML code where I upload my file.
<form action="uploader.v1.2.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" accept=".csv"/>
<input type="submit" value="Upload File" name="submit" />
</form>
This is my PHP code for accepting the file.
$sheetData = array();
if (($handle = fopen($_FILES["fileToUpload"]["name"], "r")) !== FALSE)
{
while (($dat = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sheetData[] = $dat;
}
fclose($handle);
}
else
{
echo '<script language="javascript">';
echo 'alert("Error Uploading File")';
echo '</script>';
}
Could anyone tell me why I cannot upload files that have different file names. Any help would be appreciated. Just to reiterate, I am a PHP beginner
Replace your upload handler lines with these:
if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], YOUR_UPLOAD_DIRECTORY_PATH_AND_FINAL_FILENAME)):
if (($handle = fopen(YOUR_UPLOAD_DIRECTORY_PATH_AND_FINAL_FILENAME, "r")) !== FALSE)
{
while (($dat = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sheetData[] = $dat;
}
fclose($handle);
}
else
{
echo '<script language="javascript">';
echo 'alert("Error Uploading File")';
echo '</script>';
}
endif;
Where "YOUR_UPLOAD_DIRECTORY_PATH_AND_FINAL_FILENAME" represents a directory path and filename on your server: e.g: "/wamp/www/uploads/test.csv".
Based on your code, there's no reason why a file with a different name wouldn't work. Most likely it is the CSV format that is slightly different.
In fact, parsing CSV can be very complex especially if you need to support "all csv files". So rather than use the built-in PHP functions, which can be quite limited, I'd suggest using a specialized package such as this one:
First of all, the attribute accept
must contains MIME type:
text/comma-separated-values, text/csv, text/anytext, application/csv, application/excel, application/vnd.msexce, application/vnd.ms-excel
Secondly, CSV is a text format and file extension may be differ than .csv. But if you want to filter by extension, you can do it on clien-side using FileAPI (https://w3c.github.io/FileAPI/).