File upload security? Proving a spreadsheet is really a spreadsheet

Topics: User Forum
Jul 4, 2009 at 10:05 PM

Has anyone written any code which can verify that the file uploaded really is an Excel document? I have this but I don't know if it's enough:

if ( strToLower ( $path_info['extension'] ) != 'xls' )

    {

    echo "You did not upload an Excel 2000/XP/2003 (.xls) file, please go back and try again!<br />\n";

    end_HTML ( );

    }

 

$objReader = PHPExcel_IOFactory::createReader('Excel5');

$objReader->setReadDataOnly(true);

 

if ( ! $objPHPExcel = $objReader->load($_FILES['uploadedfile']['name']) )

    {

    echo "There was a problem reading the Excel file, please check the format and contents of this file and try again!<br />\n";

    end_HTML ( );

    }

Developer
Jul 4, 2009 at 10:43 PM
Edited Jul 4, 2009 at 10:44 PM

1.
With Excel5 reader, if the file is not a valid BIFF5 or BIFF8 Excel file (covering Excel 5.0, 95, 97, 2000, XP, 2003 formats), then it will throw an exception.

Therefore you can do like this:

$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objReader->setReadDataOnly(true);

try {
    $objPHPExcel = $objReader->load($_FILES['uploadedfile']['name']);
} catch (Exception $e) {
    // something went wrong
    echo $e->getMessage();
    exit;
}

It may not be good to discard uploaded files just because file extension is not as expected. Users can accidentally alter file extension to something other than xls. The above will read the file even with wrong file extension.

2.
You may instead want to use the below method. It works similarly, but will automatically resolve file type and invoke the correct reader. You probably also want to accept Excel 2007 (xlsx files). With the below code you don't have to worry whether users have saved as xlsx or xls (or even csv).

try {
    $objPHPExcel = PHPExcel_IOFactory::load($_FILES['uploadedfile']['name']);
} catch (Exception $e) {
    // something went wrong
    echo $e->getMessage();
    exit;
}

The drawback with this method is that you cannot use setReadDataOnly(true), but with recent improvements in speed (since PHPExcel 1.6.7), there is not much gain anymore using that so I wouldn't worry about that.

Download latest source code here:
http://phpexcel.codeplex.com/SourceControl/ListDownloadableCommits.aspx

Jul 4, 2009 at 11:11 PM

I really like 2. better!

 

Are there any other security tips?

Developer
Jul 4, 2009 at 11:24 PM

>> Are there any other security tips?

We should probably not call this a security tip. Rather it's about providing good error messages to the user if they upload wrong files accidentally. The above should suffice.