CodeIgniter Forums
File uploading: Do not require a file to be uploaded - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: File uploading: Do not require a file to be uploaded (/showthread.php?tid=20530)

Pages: 1 2


File uploading: Do not require a file to be uploaded - El Forum - 07-13-2009

[eluser]sjmiller85[/eluser]
I'm creating a form using the form validation library, as well as the file uploading library. With it, I have an option for a user to either link to a website, or upload a file (must be one or the other). Unfortunately though, should the user not upload a file in the form, but rather post a link to a website, it returns the exception: "You did not select a file to upload." The problem with this is that not always will a user need to upload a document, so long as the other field is filled in, yet I am having a bugger of a time trying to figure out how I am to allow the user to not upload a file without having that exception returned. What needs to happen to not require a file to be uploaded in the form? I've trying mixing around with the if( $this->upload->do_upload() ) {} portion, but in doing so, I am preventing all other exceptions associated with file uploads that could happen should one upload a file, to be raised (file size, file type, etc...). What needs to happen to not require a file upload to happen in a form?


File uploading: Do not require a file to be uploaded - El Forum - 07-13-2009

[eluser]garymardell[/eluser]
I assume you have something like this a callback to do the upload.

Code:
function _upload_file()
    {
    
        // try to upload the form return error if failed.
        
        $config['upload_path'] = './public/uploads/sermons/';
        $config['allowed_types'] = 'mp3|jpg|jpeg';
        $config['max_size']    = '2000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        
        $this->load->library('upload', $config);
                
        
        if (!$this->upload->do_upload("sermon"))
        {
            $this->form_validation->set_message('_upload_file', 'The file could not be uploaded.');
            return false;
        }
        else
        {
            return true;
        }
    }

Now in the callback you could add a check to see if the other field was filled in.

Code:
function _upload_file()
    {
        if(!empty($this->input->post("field_name")))
        {
            return true;
        }
    
        // try to upload the form return error if failed.
        
        $config['upload_path'] = './public/uploads/sermons/';
        $config['allowed_types'] = 'mp3|jpg|jpeg';
        $config['max_size']    = '2000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        
        $this->load->library('upload', $config);
                
        
        if (!$this->upload->do_upload("sermon"))
        {
            $this->form_validation->set_message('_upload_file', 'The file could not be uploaded.');
            return false;
        }
        else
        {
            return true;
        }
    }

This will check if the other field is filled in and if it is then it will return true, so the upload will not be done and for the validation purposes will appear successful (basically skipped).


File uploading: Do not require a file to be uploaded - El Forum - 07-13-2009

[eluser]sjmiller85[/eluser]
Very nice! Didn't even think about that!

... But... this is my mistake for not clarifying earlier. For the two fields, it is a require at least 1, if not both. So the user could link a website, or upload a file, or both, as long as there is at least one. My apologies for not clarifying earlier, blew over my head when writing up the first post. Would I have to extend that if() control a bit to get it to check if the _POST variable as well as the _FILE variable is set or if it is one or the other, etc?


File uploading: Do not require a file to be uploaded - El Forum - 07-13-2009

[eluser]Michael Wales[/eluser]
Yeah - if you are doing a this-or-that comparison, the standard Form Validation library won't be of much assistance (at least in terms of checking if a field has content).


File uploading: Do not require a file to be uploaded - El Forum - 07-13-2009

[eluser]garymardell[/eluser]
Code:
function _upload_file()
    {
      
    
        // try to upload the form return error if failed.
        
        $config['upload_path'] = './public/uploads/sermons/';
        $config['allowed_types'] = 'mp3|jpg|jpeg';
        $config['max_size']    = '2000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        
        $this->load->library('upload', $config);
                
        
        if ($this->upload->do_upload("sermon") || !empty($this->input->post('field_name')) || $something_else == true)
        {
            return true;
        }
        else
        {
            $this->form_validation->set_message('_upload_file', 'The file could not be uploaded.');
            return false;
            
        }
    }

Maybe, but yeah you can see that its fairly easy to see what checks to be made, you'd probably be better off doing a series of checks, so order the fields in priority so, check if file uploaded, return true if it was, else check if another field was filled in, else check some other field was filled in, else return false with an error message saying one of the fields should be filled in.


File uploading: Do not require a file to be uploaded - El Forum - 07-14-2009

[eluser]sjmiller85[/eluser]
So right now, I am going to use an if/elseif/elseif/else structure to run it through the 2 fields. First if regards whether or not they uploaded a file and typed in a URL. Second if contains the necessary portion for if they type out a URL but don't upload a file, third is if they upload a file but no website, the final else is if the above three failed, return an error.

My question is, regarding the if of they typed out a link, but didn't upload a file, I am using the statement:

Code:
//code before
} elseif ( !empty($_POST['WebsiteLink']) && ! $this->upload->do_upload() ) {
//code after

Now this is a problem, because it is telling it if the file failed at all, not just if they didn't upload a file. They very well could have uploaded a file that was incorrect in any number of ways, and would trigger that. My thoughts are to extend that a bit to include another boolean to see if $this->upload->display_errors() == the exception of "You did not select a file to upload." Or whatever the error is. Any advice on how to resolve that issue? Thanks again for all the assistance thus far!


File uploading: Do not require a file to be uploaded - El Forum - 07-14-2009

[eluser]garymardell[/eluser]
Okay, well ill help you out just need to get something clear.

How do you want it to work. I need to know clearly what fields are required and which ones have priority.

So for example
if they uploaded a file use that.
Else if they filled in field x use that
else it failed.


File uploading: Do not require a file to be uploaded - El Forum - 07-14-2009

[eluser]sjmiller85[/eluser]
I will go into much more in-depth detail. Unfortunately, I am unable to copy and paste code.

The form itself is an application for the user to apply for a position. They enter in the following fields (by _POST name):

RealName (type="text"),
Email (type="text"),
EmailValidate (type="text"),
UserName (type="text"),
PasswordValidate (type="text"),
TeamPositionID (multiselect),
Experience (type="text"),
WebsiteLink (type="text"),
userfile (upload),
MiscAppNotes (type="text")

The fields in question are: "WebsiteLink" and "userfile". I am using the form validation library for the rest of the fields. the function is straightforward, run the validation, if it fails, return the errors, use set_value() to fill in the fields, have them try again. If the form validation succeeds, this is where it gets hairy. For the form validation config file, the fields marked as required are ALL but "WebsiteLink", "userfile", and "MiscAppNotes". Of those three, "WebsiteLink" and "userfile" are the two in question with regards to this topic. For them. The user may link us to a website, and/or upload a file. I wouldn't necessarily classify it as having an order of precedence, since they can do either or both, so long as there is at least one. Without being able to copy and paste, I am going to fat finger the general construct of the function, omitting the database queries, the variable names, all the irrelevant parts:

Code:
function apply() {
    $this->load->library('form_validation');

    if($this->form_validation->run() == FALSE) {
        //Load the page, make the necessary queries relevant to the page load, etc.. etc..
    } else {
        $config['upload_path'] = $location;
        $config['allowed_types'] = $allowedTypes;
        // etc.. etc..
        
        $this->load->library('upload',$config);

        //escape all the $_POST variables, md5 the password, etc.. etc..

        //Now begins the part in question
        if ($this->upload->do_upload() && !empty( $_POST['WebsiteLink'] )) {
            //determine upload data, run a query into the database to store
            //all the information for both the file and the website link,
            //as well as the rest of the form that was filled out
        } elseif ( !$this->upload->do_upload() && !empty( $_POST['WebsiteLink'] )) {
            //Same deal as the last one, only exclude the file.  Now the problem that
            //I see with doing this, is that it will only call to this portion of the
            //if statement if there is any problem whatsoever with the file, be it the
            //wrong type (I am only allowing .zip), too big in size, etc..  Not only
            //if there was no file uploaded, this encompasses any reason for a file
            //not getting uploaded.
        } elseif ( $this->upload->do_upload() && !empty( $_POST['WebsiteLink'] )) {
            //This will get called if the user uploaded a file but did not post a link,
            //as with the previous, run the data in the database, etc.. etc.. without
            //a file upload
        } else {
            //return errors and have them try again.
        }
    }
}

I apologize if there are any syntax errors above, that was all fat fingered in a hurry. That is the general gist of the function that is being used. Fairly straightforward.

To sum up, with regards to the two fields ("WebsiteLink" and "userfile"), at least one of the two (if not both) must be filled out. They can upload a file, or link a website, or both, and I am not 100% certain on how to process the information with regards to the upload library, since I need to determine whether or not it returns an exception regarding not uploading a file, vice trying to upload one, but having it return a plethora of errors that could potentially occur. Any leads? I thank you sincerely for your assistance with this!

EDIT: For some reason that I cannot recall at this point, I also attempted to use !isset($_FILE) in the my script as well, but was telling myself that for a reason that I cannot remember, that would not suffice as a substitute for !$this->upload->do_upload(). I tried using it again and winded up getting double the errors when uploading a file. It would repeat the error twice if I did that. Can't quite recall why I was telling myself it wouldn't work, other than the double error (which I honestly am not sure why it's doing that), but something was stopping me (other than the aforementioned exception being raised).


File uploading: Do not require a file to be uploaded - El Forum - 07-14-2009

[eluser]garymardell[/eluser]
Well you will not want to call do_upload more than once.


Code:
$upload = $this->upload->do_upload();

if($upload !== FALSE && !empty($this->input->post("WebsiteLink")))
{
  // both have succeeded store info
  return true;
}
elseif($upload == FALSE && !empty($this->input->post("WebsiteLink")))
{
  // just store the website link
  return true;
}
elseif($upload !== FALSE && empty($this->input->post("WebsiteLink")))
{
  // just store the file as the website link was empty
  return true;
}
else
{
  $this->form_validation->set_message('_upload_file', 'The file could not be uploaded.');
  return false;
}



File uploading: Do not require a file to be uploaded - El Forum - 07-14-2009

[eluser]sjmiller85[/eluser]
That confirms it:

You are made of pure awesome. Thank you very much for your assistance with this, it fixed my problem!