Reputation: 2259
This question has been asked several times, but as it turns out all of the answers I have come across have been wrong.
I'm having a problem validating whether a file is a CSV or not. Users upload a file, and the application checks to see if fgetcsv works in order to make sure it's a CSV and not an Excel file or something else. That has been the traditional answer I'm finding via Google.
e.g.:
if ($form->file->receive()) {
$fileName = $form->file->getFileName();
$handle = fopen($fileName, 'r'); // or 'w', 'a'
if (fgetcsv($handle)) {
die('sos yer face');
}
if ($PHPExcelReader->canRead($fileName)) {
die('that\'s what she said');
}
}
What happens with the above is 'sos yer face' because fgetcsv validates as true no matter what you give it if your handle comes from fopen($fileName, 'r') as long as there is a file to read; and fgetcsv always false when using fopen($fileName, 'w') or 'a' because the pointer will be initiated at the EOF. This is according to the php.net documentation.
Maybe what I'm saying is ridiculous and I just don't realize it. Can anyone please fix my brain.
Upvotes: 1
Views: 583
Reputation: 8003
The problem with validating whether or not a file is a CSV file is that CSV is not a well-defined format. In fact, by most definitions of CSV, just about any file would be a valid CSV, treating each line as a row with a single column.
You'll need to come up with your own validation routine specific to the domain you are using it in.
Upvotes: 1