fedejp
fedejp

Reputation: 970

How can I offer to upload a file without making it required

What I'm doing is a form and part of the thing that you can upload is a file:

<input type="file" name="userfile" size="20" />

It works fine but the only problem is that if the user doesn't select a file the program crashes. I tried to make it not required by adding an if instruction in the controller:

if ($this->input->post('userfile')) {
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '100';
            $config['max_width']  = '1024';
            $config['max_height']  = '768';

            $this->load->library('upload', $config);
            $imagen = $this->upload->do_upload();
        }

But this lousy attempt doesn't seem to work because $this->input->post('userfile') doesn't contain anything, regardless if the user selects a file or not.

So the question is: How can I know if the user selected a file (or not) so that I can properly handle it on my controller?

Upvotes: 0

Views: 55

Answers (2)

kirushanths
kirushanths

Reputation: 131

in PHP, <input> elements with the type="file" will automatically populate the PHP array $_FILES instead of $_POST, which codeigniter's $this->input->post() function looks in.

http://php.net/manual/en/reserved.variables.files.php

Therefore, You can check if the user has uploaded any files by doing the following:

    if($_FILES['userfile']['error'] == UPLOAD_ERR_OK)
    {
       // A file was uploaded

            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '100';
            $config['max_width']  = '1024';
            $config['max_height']  = '768';

            $this->load->library('upload', $config);
            $imagen = $this->upload->do_upload();
    }

Upvotes: 1

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

if($_FILES['userfile']['error'] == UPLOAD_ERR_OK)
{
   // A file was selected and uploaded to the server for further processing
}

Other possible values for the error field if you need to give more extensive feedback.

Upvotes: 1

Related Questions