ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Extended form_validation: now with file checking :)

July 21, 2009 7:36pm

Subscribe [25]
  • #61 / Dec 23, 2009 7:32am

    nkm82

    10 posts

    Is xxs_clean a callback function?  Or did you mean to type xss_clean?

    Also, I did use version 2.1.  I’ve modified it a little bit, so that the function names were clear, removed a couple that were unnecessary, fixed some code that was a bit redundant and made some changes so that they conform more to the CodeIgniter Upload class.

    I’ve posted the code, here are the links:

    Test Controller
    Test View
    Custom Form_validation class

    Thanks djenniex, neat code. By the way, it was still failing when no file specified, so I made a little modification to fix it.

    Now, if no file is specified but the field is not required, no error is thrown and the validation continues.

    Note: The following code it’s for djenniex’s version.

    // It's a file, so process it as a file
                $postdata = $_FILES[$row['field']];
    
                // Is the file required?
                $file_required = in_array('file_required', $rules);
    
                // Before doing anything check for errors
                if ($postdata['error'] !== UPLOAD_ERR_OK)
                {
                    switch ($postdata['error'])
                    {
                        case 1:    // UPLOAD_ERR_INI_SIZE
                            $error = $this->CI->lang->line('upload_file_exceeds_limit');
                            break;
    
                        case 2: // UPLOAD_ERR_FORM_SIZE
                            $error = $this->CI->lang->line('upload_file_exceeds_form_limit');
                            break;
    
                        case 3: // UPLOAD_ERR_PARTIAL
                            $error = $this->CI->lang->line('upload_file_partial');
                            break;
    
                        case 4: // UPLOAD_ERR_NO_FILE
                            // Set the error only if the field is required
                            if ($file_required) $error = $this->CI->lang->line('upload_no_file_selected');
                            break;
    
                        case 6: // UPLOAD_ERR_NO_TMP_DIR
                            $error = $this->CI->lang->line('upload_no_temp_directory');
                            break;
    
                        case 7: // UPLOAD_ERR_CANT_WRITE
                            $error = $this->CI->lang->line('upload_unable_to_write_file');
                            break;
    
                        case 8: // UPLOAD_ERR_EXTENSION
                            $error = $this->CI->lang->line('upload_stopped_by_extension');
                            break;
    
                        default:
                            if ($file_required) $error = $this->CI->lang->line('upload_no_file_selected');
                            break;
                    }
    
                    if (isset($error))
                    {
                        // Build the error message
                        $message = sprintf($error, $this->_translate_fieldname($row['label']));
    
                        // Save the error message
                        $this->_field_data[$row['field']]['error'] = $message;
    
                        if ( ! isset($this->_error_array[$row['field']]))
                        {
                            $this->_error_array[$row['field']] = $message;
                        }
    
                        return FALSE;
                    }
                }
    
                $_in_array = FALSE;
    
                // If the field is blank, but NOT required, no further tests are necessary
                $callback = FALSE;
                if ( ! $file_required && $postdata['size'] == 0)
                {
                    // Before we bail out, does the rule contain a callback?
                    if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
                    {
                        $callback = TRUE;
                        $rules = (array('1' => $match[1]));
                    }
                    else
                    {
                        return;
                    }
                }
  • #62 / Jan 23, 2010 2:33pm

    bradleyg

    7 posts

    Any reason why an error message isn’t being displayed when no file is selected?

    CONTROLLER

    $this->form_validation->set_rules('userfile','Image','file_required');

    VIEW

    
    <label for="userfile">Select Photo</label>
    <input type="file" name="userfile" id="userfile" />
    <?php if (form_error('userfile')): echo '<span class="error">'.form_error('userfile').'</span>'; endif; ?>
    

    I have the same problem as this. It’s weird that when you use

    <?php echo validation_errors(); ?>

    the error is there.

    I used this dirty hack for the time being:

    <?php if(strpos(validation_errors(), "No file selected") !== false) { echo 'No file selected'; } ?>

    And placed it just underneath

    <?php echo form_error('userfile') ?>

    . This way all the other errors work fine.

  • #63 / Feb 09, 2010 12:30am

    umefarooq

    690 posts

    nice extension i really like it but one thing i want to ask can we use it for multiple file upload or array of files uploading. for example

    <input type="file" name="upload[]" />
    <input type="file" name="upload[]" />
    <input type="file" name="upload[]" />

    will it work for it.

  • #64 / Feb 23, 2010 3:32pm

    phpcoder2010

    1 posts

    does anyone know why file_max_size[xxx] isnt working? im using this:

    $this->form_validation->set_rules('blog_banner', 'Blog Banner', 'file_required|file_allowed_type[image]|file_max_size[100KB]');

    everything but file size max works can anybody help me?

    thanks guys

    /* update */

    found my problem lol using it wrong way around was using file_max_size when its file_size_max lol :D spent hours banging me head with this too lol

  • #65 / Sep 02, 2010 3:41pm

    Patroklo

    18 posts

    First of all, sorry about my bad english, if you have some trouble understanding something that I have said, please ask.

    Second: Thanks for the library! That’s what I was searching for a long time. Now I can use file and form validation in the same controller without problems.

    I’m making a new version of my web and started using it for the file uploading forms(almost all are images) and for now i dont had any problem until today.

    The thing is that I have learned that if you make a bmp file in the windows paint and change the extension from bmp to jpg the form_validation thinks that it’s a jpg, and it seems that the upload library of codeigniter has the same problem. So I have made a little change in the file_allowed_type function of your library to resolve that. Now instead of using the “type” parameter of the $_FILES variable, I make a new “type” parameter from the uploaded file and, using a MIME function of the upload library I compare the new “type” instead of using file extension comparations.

    function file_allowed_type($file,$type)
        {
          
            //is type of format a,b,c,d? -> convert to array
            $exts = explode(',',$type);
                    
            //is $type array? run self recursively
            if(count($exts)>1)
            {
                foreach($exts as $v)
                {
                    $rc = $this->file_allowed_type($file,$v);
                    if($rc===TRUE)
                    {
                        return TRUE;
                    }
                }
            }
            
            //is type a group type? image, application, word_document, code, zip .... -> load proper array
            $ext_groups = array();
            $ext_groups['image'] = array('jpg','jpeg','gif','png');
            $ext_groups['application'] = array('exe','dll','so','cgi');
            $ext_groups['php_code'] = array('php','php4','php5','inc','phtml');
            $ext_groups['word_document'] = array('rtf','doc','docx');
            $ext_groups['compressed'] = array('zip','gzip','tar','gz');
            
          $retorno = false;
          
                    //with this we get the TRUE MIME of the file, not the fake one
                    //'cause upload bug
                    $ftype = 'application/octet-stream';
                    $finfo = @new finfo(FILEINFO_MIME);
                    $fres = @$finfo->file($file['tmp_name']);
                    if (is_string($fres) && !empty($fres)) {
                       $tipo_archivo = $fres;
                    } 
                    else
                    {
                    return False;
                    $this->set_message('file_allowed_type',"Error, tipo inexistente.");
                    }
          
          
          $CI =& get_instance();    
          $CI->load->library('Upload');
          
            
          $tipo = $ext_groups[$exts[0]];
    
                foreach($tipo as $extension)
                {
                    $mimes_internos  = $CI->upload->mimes_types($extension);
                    if(is_array($mimes_internos))
                    {
                            if (in_array($tipo_archivo,$mimes_internos))
                            {
                            $retorno = true;
                            }
                    }
                    else
                    {
                            if ($mimes_internos == $tipo_archivo)
                            {
                            $retorno = true;
                            }
                    }
    
                }
            
            
            
       
    
          if($retorno == true)
            {
            return TRUE;
            }
            else
            {
            $this->set_message('file_allowed_type',"%s no puede ser del formato $tipo_archivo.");
            return  false;   
            }
            
        }

    Again, if you have some problem understanding me, ask whatever you want.

  • #66 / Nov 08, 2010 1:17am

    bravonet

    2 posts

    nice extension i really like it but one thing i want to ask can we use it for multiple file upload or array of files uploading. for example

    <input type="file" name="upload[]" />
    <input type="file" name="upload[]" />
    <input type="file" name="upload[]" />

    will it work for it.

    i had the same problem too..

    i had try with few test

    for ($i=0; $i < $num_files ; $i++) {
           $this->form_validation->set_rules("userfile[$i]","File","file_required|file_size_max[2048KB]|file_size_min[10KB]|file_allowed_type[image]");
       }

    this is not working in the validation

    for ($i=0; $i < $num_files ; $i++) {
    $file_field_name[$i] = $_FILES['userfile']['name'][$i];
           $this->form_validation->set_rules($file_field_name[$i],"File","file_required|file_size_max[2048KB]|file_size_min[10KB]|file_allowed_type[image]");
       }

    this is not working too.

    please point out my mistake. or the library isn’t working with multiple upload?

  • #67 / Sep 22, 2011 5:43am

    Auto Banned

    1 posts

    can this libray used at CI 2.0.2 ? because, i try this tutorial it seem didnt work at my apps. sorry my bad english

  • #68 / Sep 13, 2012 1:27pm

    AMCerasoli

    5 posts

    I’m just starting with CI, I have placed the file MY_Form_validation.php in applications/libraries and then as the user guide says I have just load normally the library

    $this->load->library('form_validation');

    . B

    But I’m getting: Fatal error: Call to undefined method CI_Form_validation::CI_Form_validation() in /web/htdocs/www.website.com/home/application/libraries/MY_Form_validation.php on line 50

    Am I doing something wrong? thanks.

    Good extension BTW. 😊

  • #69 / Sep 13, 2012 2:27pm

    TWP Marketing

    596 posts

    I’m just starting with CI, I have placed the file MY_Form_validation.php in applications/libraries and then as the user guide says I have just load normally the library

    $this->load->library('form_validation');

    . B

    But I’m getting: Fatal error: Call to undefined method CI_Form_validation::CI_Form_validation() in /web/htdocs/www.website.com/home/application/libraries/MY_Form_validation.php on line 50

    Am I doing something wrong? thanks.

    Good extension BTW. 😊

    First, you’re responding to a thread that is two years old, which means it was written for an older version of CI. Which version are you using?

    I assume you are EXTENDING the CI form validation library and not writing your own?

    Show us your code in MY_Form_validation.php, specifically look at line 50 and at the class declaration at the top of MY_Form_validation.php which should extend CI_Form_validation like this:

    class MY_Form_validation extends CI_Form_validation {

    Check your config/config.php and be sure this line is present:

    ...
    $config['subclass_prefix'] = 'MY_';
    ...
  • #70 / Sep 14, 2012 3:33pm

    AMCerasoli

    5 posts

    First, you’re responding to a thread that is two years old

    Wow… I didn’t know… Hahahaha

    The problem was that I had two files in the server with the same name but with different capitalization (MY_Form.. and MY_form) and was reading the wrong file, the one that I was using to make some test…

    After that there is no error but the features that it says it has seems to not work at all. It’s like there was no extension.

    I assume you are EXTENDING the CI form validation library and not writing your own?

    Yes. I’m not writing my own.

    Everything was like you said it should (Classes, config) but it doesn’t work. I guess this should be added to the official framework, I don’t know why this is spitted into a class and a helper… I have solved the problem differently. thanks anyway. Oh and BTW if the forum allow to post something after 2 years is because there shouldn’t be no problem with that…

     

  • #71 / Sep 14, 2012 3:44pm

    TWP Marketing

    596 posts

    So you solved your problem?

    Re the old thread, you can respond unless the site moderators lock it, but the original problem on old thread usually relate to an earlier version, plus the OP may no longer be around to respond with their solution. It’s usually better to start a new thread just so people don’t have to read the whole thing to get the situation. But it is totally your choice.

  • #72 / Sep 14, 2012 3:57pm

    AMCerasoli

    5 posts

    So you solved your problem?

    Yhea, but not as I wanted to… :down: I’m first checking if the “normal” form was correctly submitted and then checking if the file was correctly submitted and sending a variable to the view in case it wasn’t, of course I need to check if the variable has been set before trying to show its content in the view otherwise I would get an error aaannndd, all this makes my solutions more like a hack than a real solution… But anyway thanks you for taking the time.

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases