CodeIgniter - 文件上传需要验证

Posted

技术标签:

【中文标题】CodeIgniter - 文件上传需要验证【英文标题】:CodeIgniter - File upload required validation 【发布时间】:2012-08-30 15:10:55 【问题描述】:

我有 2 个文本字段和 1 个文件上传都是必需的。当我只需要文本字段时,一切正常,但是当我需要文件上传时,验证错误仍然显示需要文件,即使我选择了一个。有人知道我在做什么错吗?非常感谢。

//查看

<?php echo form_open_multipart('add'); ?>

<fieldset>
    <input type="text" name="name" /><br>
    <input type="text" name="code" /><br>
    <input type="file" name="userfile" /><br><br>
    <input type="submit"value="Add" />
</fieldset>

<?php echo form_close(); ?>

//控制器

public function add() 

    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('code', 'Code', 'required');
    //$this->form_validation->set_rules('userfile', 'Document', 'required');
    //when the above line is active the upload does not go through

    if ($this->form_validation->run() == FALSE) 

        $data['page_view'] = $this->page_view;
        $data['page_title'] = $this->page_title;
        $this->load->view('template', $data);
    
    else
    
        $this->load->library('upload');

        if (!empty($_FILES['userfile']['name']))
        
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';     

            $this->upload->initialize($config);

            if ($this->upload->do_upload('userfile'))
            
                $img = $this->upload->data();
                $file_name = $img['file_name'];

                $name = $this->input->post('name');
                $code = $this->input->post('code');

                $this->load->model('create', 'create_model');
                $this->create_model->create_entry($name, $code, $file_name);

                $data['page_view'] = $this->page_view;
                $data['page_title'] = $this->page_title;
                $this->load->view('template', $data);
            
            else
            
                echo $this->upload->display_errors();

            
        
    

【问题讨论】:

我有个建议,最好也插入你的html 好的,我添加了 html,虽然它非常基本,但不确定它是否会有所帮助。 这可能是因为您尝试上传的文件太大。尝试上传一个较小的文件,如果可行,那么您可能需要更改php.ini 中的设置,以便您可以上传更大的文件。另外,如果你想快速调试,我建议你在$_FILES超全局上做一个var_dump(),看看文件上传的错误代码是什么。 【参考方案1】:

CodeIgniter 文件上传可选......完美运行...... :)

--------- 控制器 ---------

function file()

 $this->load->view('includes/template', $data);


function valid_file()

 $this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');

 if ($this->form_validation->run()==FALSE) 
 
    $this->file();
 
 else
 
  $config['upload_path']   = './documents/';
  $config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
  $config['max_size']      = '1000';
  $config['max_width']     = '1024';
  $config['max_height']    = '768';

  $this->load->library('upload', $config);

  if ( !$this->upload->do_upload('userfile',FALSE))
  
    $this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());

    if($_FILES['userfile']['error'] != 4)
    
        return false;
    

  
  else
  
    return true;
  

我只是使用这行使其成为可选,

if($_FILES['userfile']['error'] != 4)

 return false;


$_FILES['userfile']['error'] != 4 is for file required to upload.

您可以通过使用$_FILES['userfile']['error'] != 4 使其变得不必要,然后它将传递此错误以获取所需的文件,并通过使用 return false 很好地处理其他类型的错误, 希望它对你有用....

【讨论】:

【参考方案2】:

    设置规则检查文件名(如果表单是多部分的)

    $this-&gt;form_validation-&gt;set_rules('upload_file[name]', 'Upload file', 'required', 'No upload image :(');

    如下覆盖$_POST数组:

    $_POST['upload_file'] = $_FILES['upload_file']

    然后做:

    $this-&gt;form_validation-&gt;run()

【讨论】:

【参考方案3】:

你可以使用回调函数, 像这样

  $this->form_validation->set_rules('userfile', 'Document', 'callback_file_selected_test');

    if ($this->form_validation->run() == FALSE) 
         //error
     
    else
           // success       
      

function file_selected_test()

    $this->form_validation->set_message('file_selected_test', 'Please select file.');
    if (empty($_FILES['userfile']['name'])) 
            return false;
        else
            return true;
        

【讨论】:

【参考方案4】:

你可以通过重写 CI_Form_Validation 的 Run 函数来解决它

将此函数复制到扩展 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;

【讨论】:

【参考方案5】:

我找到了一个完全符合我要求的解决方案。

我变了

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))

    $this->form_validation->set_rules('userfile', 'Document', 'required');

【讨论】:

您是否尝试过验证所需的文件类型? 多文件上传怎么办?【参考方案6】:

检查此表单验证扩展库可以帮助您验证文件,当您验证上传字段时,当前表单验证将其视为值为空的输入字段,看看这个表单验证库的非常好的扩展

MY_Formvalidation

【讨论】:

以上是关于CodeIgniter - 文件上传需要验证的主要内容,如果未能解决你的问题,请参考以下文章

CodeIgniter文件上传验证ppt和pptx文件

codeigniter 4 多文件验证

文件上传需要大量时间 Codeigniter

即使选择了文件,也会显示CodeIgniter文件验证

CodeIgniter 中视频文件上传的奇怪问题

将表单文件附加到电子邮件,Codeigniter