Trongate Docs
switch to dark modeswitch to dark mode
»
»
Uploading Files

Uploading Files

Trongate has a built-in method that can assist in uploading files.  The method is called 'upload_file'.

The upload_file() method accepts one argument - an array of configuration options, typically called '$config'.

$this->upload_file($config);

A Closer Look At $config

The upload_file method accepts an array of configuration options.  This array may contain the following properties:

  • destination - the directory where the submitted file should be uploaded to
  • new_file_name - an optional property indicating if the file should be renamed (to a random string) upon upload

Below is an example of the upload_file() method being invoked in a situation where the submitted file should be added to a directory called 'files' which is located inside the 'public' direction.  Here we are also declaring that our uploaded file should be given a random file name.  

Did You Know?
Giving uploaded files a random file name can add a helpful layer of additional security to web apps.

$config['destination'] = '../public/files';
$config['new_file_name'] = true;
$this->upload_file($config);

Just To Let You Know
You may have to take a moment to modify the permissions on your target upload folder to make file uploading work.

File Uploaded - What Now?

Once a file has been successfully uploaded it's for you, the developer, to decide what happens next.  You could send your user to some kind of 'success' page.  Alternatively, you could just use flashdata to return your user to some other page such as a basic record details page.

The Complete File Upload Method

Below is some sample code showing you a complete method for uploading files.  As always, this code should just be considered a rough guide and nothing more.  You are encouraged to adjust and improvise to suit your own situation:


​function submit_upload() {
​  $this->module('trongate_security');
​  $this->trongate_security->_make_sure_allowed();

​  $submit = post('submit');

​  if ($submit == 'Upload') {
​    //let's do some validation...
    $this->validation_helper->set_rules('my_file', 'file',  'required|allowed_types[txt,csv]|max_size[2000]');    

    $result = $this->validation_helper->run();

    if ($result == true) {
      //upload the file
      $config['destination'] = '../public/files';
      $config['new_file_name'] = true;
      $this->upload_file($config);

      //set some flashdata
      set_flashdata('Your file was successfully uploaded');

      //Job done!  Send the user to another page...
      $target_url = str_replace('/submit_upload', '/show', current_url());
      redirect($target_url);

    } else {
      //validation error! Present the form again.
      $this->upload();
    }

​  }
​}​



HELP & SUPPORT

If you have a question or a comment relating to anything you've see here, please goto the Help Bar.

 
×