Take the 2-minute tour ×

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.


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.

share|improve this question
A shining example of professionalism in debug error messages. –  Justin Satyr Sep 21 '11 at 18:01
thankfully just a mockup for my learning pleasure. I would think twice before doing that in a business setting, probably –  tjb1982 Sep 21 '11 at 18:03
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
add comment

Your Answer


