*_jemarea_*

Website Development

  • Home
  • Articles
    • All articles
    • Linux
    • WordPress
    • Codeigniter
    • PHP
    • JavaScript
    • MySql
  • About
  • Contact

June 7, 2018 By jerome Leave a Comment

Upload CSV with CodeIgniter

This can be done quite easily but I would like to give an example here using Bootstrap for the layout and jQuery to trigger events and send the data to my controller.

You will have 3 areas:

  • your view with the upload button
  • your controller or helper function handling the input
  • your model in case you want to store the result

Make sure you have bootstrap and jQuery installed or at least implemented through a link.

1 The View and Upload Button

I integrate a modal in my page that I can call when a button “Upload CSV” is clicked:

 

<!-- START UPLOAD MODAL -->
<div class="modal fade" id="csv-upload-modal" role="dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><span id="modal-title">Upload CSV</span></h4>
      </div>
      <div class="modal-body">
        <form enctype="multipart/form-data" name="upload-form" id="upload-form"> 
            <table>
                <tr>
                    <td> Browse: </td>
                    <td>
                        <input type="file" class="form-control" name="csv_file" id="csv-file"  align="center"/>
                    </td>
                    <td>
                        <div class="col-lg-offset-3 col-lg-9">
                            <button type="submit" name="submit" class="btn btn-info btn-upload-csv">Send</button>
                        </div>
                    </td>
                </tr>
            </table> 
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- END UPLOAD MODAL -->

 

All you have to do is to add some jQuery to the button which should open this modal:

 

$('#upload-csv-btn').click( function() {
   $('#csv-upload-modal').modal('show');
});

The jQuery and the bootstrap can both go onto the same page or – of course – you can separate them and have your javascript in a different file.

So far so good. You should be able to open the upload popup and browse your files.

Let’s catch the information and send it to our controller.

Again, we use some jQuery to get hold of the data and push it further via Ajax:

 

$('#upload-form').submit( function(e) {
  e.preventDefault(); // don't send form as it
  $.ajax({
       method:"POST",
       url:"ajax_csv_upload",      // this is my function in the controller
       data:new FormData(this),    
       contentType:false,          // The content type used when sending data to the server.  
       cache:false,                
       processData:false,          // To send DOMDocument or non processed data file it is set to false  
       success: function(data){  
            $('#csv-upload-modal').modal('hide'); // hide the file upload modal
            $('#small-modal-title').html( 'CSV Upload' ); // set title for the small notification modal
            $('#small-modal-text').html( data );  // the data will be the notification (success or failure)
            $('#small-modal').modal('show');
       }  
  })
});

I will not get too much into the details of the success / failure behaviour there, but you get the idea: I am also using a small modal that shows up as a notification popup when the upload is done.

2 The controller function

Now let’s take a look at how the data is received by the controller.

public function ajax_csv_upload() {

....

    //* FILE UPLOAD
    if ( $_FILES["csv_file"]["name"] )
    {
      $allowed_ext = array("csv");  // set your rule for allowed extension 
      $extension = end(explode(".", $_FILES["csv_file"]["name"]));  
      if(in_array($extension, $allowed_ext))  
      {  
         $file_data = fopen($_FILES["csv_file"]["tmp_name"], 'r');
                           // THIS IS THE FIRST ROW OF YOUR CSV
                           // you might want to check the column titles to see if things are alright
                           // you could also just check if there are titles or already the data...
         $first_row = fgetcsv($file_data); 

         //* (I do a check of the titles)
         $csv_correct = true;
         $csv_correct = ( $first_row[0] == 'title1' ) ? $csv_correct : false;
         $csv_correct = ( $first_row[1] == 'title2' ) ? $csv_correct : false;
         $csv_correct = ( $first_row[2] == 'title3' ) ? $csv_correct : false;

         //* if csv_correct is true, we can move on, otherwise error (format is not correct)
         if ( $csv_correct ) {
           while($row = fgetcsv($file_data))  
           {

           	//* Do something with this data
                                        // in my case I will have
                                        $first_element = $row[0];
                                        $second_element = $row[1];
                                        $third_element = $row[2];

           } // end while
          } // end $csv_correct

    }

....
}

 

Filed Under: Codeigniter, JavaScript, jQuery, PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · jemarea.com