Codeigniter - проверка формы не работает для файлов - PullRequest
1 голос
/ 29 марта 2012

Мне нужно установить входной файл, как требуется в моем контроллере Codeigniter.Это мое form_validation:

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

и это форма:

<?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(); ?>

Но после отправки формы говорят, что файл не задан, поэтому требуемый пункт не выполняется ..Как я могу это исправить?

Ответы [ 4 ]

4 голосов
/ 29 марта 2012

Данные загрузки файла не сохраняются в массиве $_POST, поэтому их нельзя проверить с помощью библиотеки form_validation CodeIgniter. Загрузка файлов доступна для PHP с использованием массива $_FILES.

Возможно, можно напрямую манипулировать массивом $ _POST, используя данные из массива $ _FILES, до запуска проверки формы, но я этого не проверял. Вероятно, лучше всего проверить процесс загрузки библиотеки на наличие ошибок.

Кроме того, по соображениям безопасности невозможно (повторно) установить значение при перезагрузке страницы.

3 голосов
/ 04 апреля 2013

Чтобы проверка работала для файлов, вы должны проверить, пусто ли это.

как

if (empty($_FILES['photo']['name']))
      {
       $this->form_validation->set_rules('userfile', 'Document', 'required');
      }
0 голосов
/ 29 апреля 2015

вы можете решить ее, переопределив функцию Run CI_Form_Validation

скопируйте эту функцию в класс, который расширяет CI_Form_Validation.

Эта функция переопределит функцию родительского класса.Здесь я добавил только дополнительную проверку, которая может обрабатывать файл также

/**
 * 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;
}
0 голосов
/ 29 марта 2012

Вы смотрели на это ->

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);
        }
    }
}
?>

Обновление согласно комментарию:

Вы можете проверить, используя обычный php, если хотите ...

    $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';
}
...