Reading a file uploaded by form

Public

Form definition

Get raw version
php
  1. function custom_form () {
  2. $form['fieldset'] = array(
  3. '#type' => 'fieldset',
  4. '#collapsible' => FALSE,
  5. '#collapsed' => FALSE,
  6. '#title' => t('Sydney Metro Journey Time Data'),
  7. );
  8.  
  9. $form['fieldset']['data'] = array(
  10. '#type' => 'file',
  11. );
  12.  
  13. $form['#submit'][] = 'custom_do_callback';
  14. }

Submit callback

Get raw version
php
  1. function custom_do_callback($form, $form_state) {
  2. $file = file_save_upload('data', array(
  3. 'file_validate_extensions' => array('csv'),
  4. ));
  5.  
  6. if ($file !== FALSE) {
  7. try {
  8. $the_file = new SplFileObject($file->uri);
  9.  
  10. // Read line by line.
  11. while (!$the_file->eof()) {
  12. $line = $the_file->fgets();
  13. dpm($line);
  14. }
  15.  
  16. } catch (Exception $exc) {
  17. watchdog('haleluya', $exc->getTraceAsString());
  18. }
  19.  
  20. // Remove the file in temp and the pointer in the database
  21. file_delete($file);
  22. }
  23. }