Professional CodeIgniter

(singke) #1

Chapter 9: Security and Performance


280


Just as a quick reminder, here ’ s the importCsv() function again:

function importCsv(){
$config[‘upload_path’] = ‘./csv/’;
$config[‘allowed_types’] = ‘csv’;
$config[‘max_size’] = ‘2000’;
$config[‘remove_spaces’] = true;
$config[‘overwrite’] = true;
$this- > load- > library(‘upload’, $config);
$this- > load- > library(‘CSVReader’);

if(!$this- > upload- > do_upload(‘csvfile’)){
$this- > upload- > display_errors();
exit();
}
$csv = $this- > upload- > data();
$path = $csv[‘full_path’];
return $this- > csvreader- > parseFile($path);
}

To ensure that the CSV headers are all correct, you might add your security to the parseFile() function
of the CSVReader library. However, don ’ t forget that at this point in the code, all you ’ ve done is upload
a CSV file and prepare an intermediate view. This view is basically an HTML table with hidden fields
that contain the data you ’ re about to store in the Products database table.

What this means is that you have to intercept bad headers and data before they show up on the
admin_products_csv view. To do that, you will need to add a single line of code to the import()
function of the admin/products controller:

function import(){
if ($this- > input- > post(‘csvinit’)){
$data[‘dbheaders’] = $this- > db- > list_fields(‘products’);
$data[‘csv’] = $this- > MProducts- > importCsv();
$data[‘title’] = “Preview Import Data”;
$data[‘main’] = ‘admin_product_csv’;
$this- > load- > vars($data);
$this- > load- > view(‘dashboard’);
}elseif($this- > input- > post(‘csvgo’)){
if (eregi(“finalize”, $this- > input- > post(‘submit’))){
$this- > MProducts- > csv2db();
$this- > session- > set_flashdata(‘message’,’CSV data imported’);
}else{
$this- > session- > set_flashdata(‘message’,’CSV data import cancelled’);
}
redirect(‘admin/products/index’,’refresh’);
}
}

The list_fields() function provides you with a list of all the field names in a particular database
table. You will use this list of field names in your view as a final check. Since you probably don ’ t want to
delete any data from the view (because this might cause some confusion on the part of the user), the best
thing to do is mark each bad passage with a warning note, and then refuse to include the header ’ s
associated data in the final form. That way, any bad data will never be uploaded.
Free download pdf