1

i need to set a input file as required into my Codeigniter Controller. This is my form_validation:

$this->form_validation->set_rules('copertina','Foto principale','required|xss_clean');

and this is the form:

<?php echo form_open_multipart('admin/canile/nuovo'); ?>
<li class="even">
    <label for="copertina">Foto principale <span>*</span></label>
    <div class="input"><input type="file" name="copertina" value="<?php echo set_value('copertina'); ?>" id="copertina" /></div>    
</li>
<?php echo form_close(); ?>

But after the submit the form say that the file is not set, so the required clausole fails...how can i fix it?

5
  • it is empty, i tried to print the $_POST and in the array i can't find the 'copertina' field...but i i print just $_FILES['copertina']['name'] i can see the img name Commented Mar 29, 2012 at 14:59
  • set_value() sets the value from $_POST, not from $_FILES. also the form validation is for $_POST $_FILES fields are not validated by that library Commented Mar 29, 2012 at 15:01
  • oh i see...do you know a library for the file validation? Commented Mar 29, 2012 at 15:03
  • Why would you XSS clean a photo? O.o Commented Mar 29, 2012 at 16:10
  • it was a mistake, i just copy and paste from the above line Commented Mar 30, 2012 at 7:23

4 Answers 4

4

File upload data is not stored in the $_POST array, so cannot be validated using CodeIgniter's form_validation library. File uploads are available to PHP using the $_FILES array.

It maybe possible to directly manipulate the $_POST array using data from the $_FILES array, before running form validation, but I haven't tested this. It's probably best to just check the upload library process for errors.

In addition, it is not possible, for security reasons, to (re-)set the value on page reload.

Sign up to request clarification or add additional context in comments.

1 Comment

do you know a library who can validate a file input?
3

To make validation to work for files you have to check whether is it empty.

like,

if (empty($_FILES['photo']['name']))
      {
       $this->form_validation->set_rules('userfile', 'Document', 'required');
      }

Comments

0

you can solve it by overriding the Run function of CI_Form_Validation

copy this function in a class which extends CI_Form_Validation .

This function will override the parent class function . Here i added only a extra check which can handle file also

/**
 * Run the Validator
 *
 * This function does all the work.
 *
 * @access  public
 * @return  bool
 */
function run($group = '') {
    // Do we even have any data to process?  Mm?
    if (count($_POST) == 0) {
        return FALSE;
    }

    // Does the _field_data array containing the validation rules exist?
    // If not, we look to see if they were assigned via a config file
    if (count($this->_field_data) == 0) {
        // No validation rules?  We're done...
        if (count($this->_config_rules) == 0) {
            return FALSE;
        }

        // Is there a validation rule for the particular URI being accessed?
        $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;

        if ($uri != '' AND isset($this->_config_rules[$uri])) {
            $this->set_rules($this->_config_rules[$uri]);
        } else {
            $this->set_rules($this->_config_rules);
        }

        // We're we able to set the rules correctly?
        if (count($this->_field_data) == 0) {
            log_message('debug', "Unable to find validation rules");
            return FALSE;
        }
    }

    // Load the language file containing error messages
    $this->CI->lang->load('form_validation');

    // Cycle through the rules for each field, match the
    // corresponding $_POST or $_FILES item and test for errors
    foreach ($this->_field_data as $field => $row) {
        // Fetch the data from the corresponding $_POST or $_FILES array and cache it in the _field_data array.
        // Depending on whether the field name is an array or a string will determine where we get it from.

        if ($row['is_array'] == TRUE) {

            if (isset($_FILES[$field])) {
                $this->_field_data[$field]['postdata'] = $this->_reduce_array($_FILES, $row['keys']);
            } else {
                $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
            }
        } else {
            if (isset($_POST[$field]) AND $_POST[$field] != "") {
                $this->_field_data[$field]['postdata'] = $_POST[$field];
            } else if (isset($_FILES[$field]) AND $_FILES[$field] != "") {
                $this->_field_data[$field]['postdata'] = $_FILES[$field];
            }
        }

        $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
    }

    // Did we end up with any errors?
    $total_errors = count($this->_error_array);

    if ($total_errors > 0) {
        $this->_safe_form_data = TRUE;
    }

    // Now we need to re-set the POST data with the new, processed data
    $this->_reset_post_array();

    // No errors, validation passes!
    if ($total_errors == 0) {
        return TRUE;
    }

    // Validation fails
    return FALSE;
}

Comments

-1

Have you looked at this ->

http://codeigniter.com/user_guide/libraries/file_uploading.html

<?php

class Upload extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    function index()
    {
        $this->load->view('upload_form', array('error' => ' ' ));
    }

    function do_upload()
    {
        $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);

        if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());

            $this->load->view('upload_form', $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());

            $this->load->view('upload_success', $data);
        }
    }
}
?>

Update as per comment:

You can check using plain php if you like ...

    $errors_file = array(
        0=>'Success!',
        1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3=>'The uploaded file was only partially uploaded',
        4=>'No file was uploaded',
        6=>'Missing a temporary folder',
        7=>'Cannot write file to disk'
    );

if($_FILES['form_input_file_name']['error'] == 4) {
 echo 'No file uploaded';
}
if($_FILES['form_input_file_name']['error'] == 0) {
 echo 'File uploaded... no errors';
}

2 Comments

Thanks, i have already see it...but i need to check just if the input file is set and not empty
i think that this is the better solution even if is not completly integratet with the library!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.