Handling file in Drupal
2011 10 Sep

Handling files with Drupal (CSV import)

By Mukesh Agarwal

Drupal allows pretty smooth file management API for developers.. Here is a small piece of code in which I tried to take CSVs as input, process them to get the data and insert the values into the database..

  1. Create a menu item for your file upload form
  2. Define the callback for the menu item and make sure to set the form encoding
  3. Make sure that the file imported is of CSV type (check the mime type of the file uploaded)
  4. And finally get data from the csv And TA-DA :-)

Drupal allows pretty smooth file management API for developers.. Here is a small piece of code in which I tried to take CSVs as input, process them to get the data and insert the values into the database..

  1. Create a menu item for your file upload form
    function example_menu() { 
    $items = array(); 
    $items['admin/example/import'] = array(
      'title' => 'Import', 
      'page callback' => 'drupal_get_form', 
      'page arguments' => array('example_form'), 
      'access arguments' => array('allow example import'), 
      'type' => MENU_LOCAL_TASK, 
    ); 
    return $items; 
    }

     

  2. Define the callback for the menu item and make sure to set the form encoding
    function example_form() { 
    
      $form = array(); 
      $form['browser'] = array(
        '#type' => 'fieldset', 
        '#title' => t('Browser Upload'), 
        '#collapsible' => TRUE, 
        '#description' => t("Upload a CSV file."), 
      ); 
      $file_size = t('Maximum file size: !size MB.', array('!size' => file_upload_max_size()));
      $form['browser']['file_upload'] = array( 
        '#type' => 'file', 
        '#title' => t('CSV File'), 
        '#size' => 40, 
        '#description' => t('Select the CSV file to be imported. ') . $file_size
      ); 
      $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); 
      // set the form encoding type 
      $form['#attributes']['enctype'] = "multipart/form-data"; 
      return $form; 
    }

     

  3. Make sure that the file imported is of CSV type (check the mime type of the file uploaded)
    function example_form_validate($form, &$form_state) { 
      // attempt to save the uploaded file 
      $file = file_save_upload('file_upload'); 
      // check file uploaded OK 
      if (!$file) { 
        form_set_error('file_upload', t('A file must be uploaded or selected from FTP updates.')); 
      } 
      else if($file->filemime != 'text/csv') { 
        form_set_error('file_upload', t('The file must be of CSV type only.')); 
      } 
      else { 
      // set files to form_state, to process when form is submitted 
        $form_state['values']['file_upload'] = $file; 
      } 
    }

     

  4. And finally get data from the CSV
    function example_form_submit($form, &$form_state) {
      $line_max = variable_get('user_import_line_max', 1000);
      ini_set('auto_detect_line_endings', true);
      $filepath = $form_state['values']['file_upload']->filepath;
      $handle = @fopen($filepath, "r");
      // start count of imports for this upload
      $send_counter = 0;
      while ($row = fgetcsv($handle, $line_max, ',')) {
      // $row is an array of elements in each row
      // e.g. if the first column is the email address of the user, try something like
        $mail = $row[0];
      }
    }

     

And TA-DA :-) This is a very simple example of how to write code to import content using CSV. File handling APIs are much better in Drupal 7, will post about the same when we get a chance.

Featured blog

web-personalization

Personalized Content is a Proven Entity !!

Irrespective of how big a business icon or brand you are, increasing the relevance of your website will always be critical to your success.

Read More

Git Hooks

Git hooks for better codes

We are programmers and we are always on the lookout for ways to improve our code. A good and structured way of coding defines the completeness of a programmer.

Read More

Drupal ,varnish cache

Hard time with Drupal, Varnish Cache and Cookies

Using a reverse proxy server in front of a web server is usually needed for every big site and it is a very good thing to do so as reverse proxy server will handle all the anonymous traff

Read More

Say no to captcha

Say no to captcha - Various Spam Protection Methods

Maintaining high traffic websites have their own merits and demerits, the most annoying thing about them is SPAM.

Read More