Welcome Guest, Not a member yet? Register   Sign In
Upload files and Form Validation
#1

Hello everyone Smile
I am using uplaod library and form validation library.

Code:
PHP Code:
$this->form_validation->set_rules('title''title''trim|required|min_length[5]|max_length[50]|htmlspecialchars');
$this->form_validation->set_rules('upload''file''callback_handle_upload'); 

handle_upload:
PHP Code:
    function handle_upload(){
        if (isset(
$_FILES['upload']) && !empty($_FILES['upload']['name'])){
         
 if ($this->upload->do_upload('upload')){
            
// set a $_POST value for 'image' that we can use later
            
$upload_data    $this->upload->data();
            
$_POST['upload'] = $upload_data['file_name'];
            return 
true;
         
 }else{
            
// possibly do some clean up ... then throw an error
            
$this->form_validation->set_message('handle_upload'$this->upload->display_errors());
            return 
false;
         
 }
        }else{
         
 // throw an error because nothing was uploaded
         
 $this->form_validation->set_message('handle_upload'"cannot be empty");
         
 return false;
        } 

When i submit my form, and for example the title is wrong so the file is uploading to my server.
I know why this is happen, because:
PHP Code:
$this->upload->do_upload('upload'
is inside handle_upload();

I did not know how to solve this problem.
I want to show errors with Form_validation (including upload errors) and upload the file only if all the other fields are correct.

Help please?

Thank you Smile
Reply
#2

Only the client can initiate an upload, so to do what you're asking requires some amount of JavaScript or multiple form submissions on the part of the user. You would have to separate the file input from the rest of the form and only allow it to be submitted if the form validates.

However, this would require two separate form submissions. You could make it behave as a single form submission for users with JavaScript enabled by submitting the first form via AJAX, then submitting the second form (normally or via AJAX) when the response from the first form indicates that everything is valid. You could also use JavaScript to get some details about the file which could be submitted before allowing the file itself to be submitted, but this is still a multi-step process.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB