Uploading a CSV File (SugarCRM On-Demand Safe)

SugarCRM On-Demand maintains a black-list of certain php functions which cannot be included in Module-loader packages: file_put_contentsupload_file, etc.

Because of this, uploading files for custom fields isn’t as simple as reading the file from the global $_FILES and moving it to the upload directory.

Fortunately, SugarCRM provides an ImportFile class, which does exactly what we want:

    require_once 'modules/Import/sources/ImportFile.php'

    $importFile = new ImportFile($_FILES['NAME_OF_OUR_FILE_UPLOAD_FIELD']['tmp_name'], ',', '"');

We simply provide the constructor with the name of the uploaded file – $_FILES['NAME_OF_YOUR_FILE_UPLOAD_FIELD']['tmp_name'], column separator, and the text delimiter.

Now we can read each row with $importFile->getNextRow():

    require_once 'modules/Import/sources/ImportFile.php'

    $importFile = new ImportFile($$_FILES['NAME_OF_OUR_FILE_UPLOAD_FIELD']['tmp_name'], ',', '"');

    // Check if can read file
    if ($importFile) {

        $values = array();
        while ($row = $importFile->getNextRow()) {
            $values[] = $row;

While On-Demand’s loader restrictions can cause some headaches, using this class for CSV uploading and parsing is actually more conveinent than typing it out manually.

More useful methods:

  • getFieldCount
  • autoDetectCSVProperties
  • fileExists
  • hasHeaderRow
  • getTotalRecordCount
  • getHeaderColumns