Für den Dateiupload ist eine Validierung in CodeIgniter erforderlich

Lesezeit: 7 Minuten

Benutzeravatar von Staysee
Bleibsee

Ich habe 2 Textfelder und 1 Datei-Upload, die alle erforderlich sind. Alles funktioniert, wenn ich nur die Textfelder benötige, aber wenn ich den Dateiupload benötige, bleibt der Validierungsfehler bestehen und besagt, dass eine Datei erforderlich ist, obwohl ich eine ausgewählt habe. Was mache ich falsch?

//Ansicht

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

//Regler

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

  • Ich habe einen Vorschlag, fügen Sie besser auch Ihren HTML-Code ein.

    – Rot

    6. September 2012 um 4:32 Uhr

  • Okay, ich habe das HTML hinzugefügt, es ist jedoch sehr einfach, ich bin mir nicht sicher, ob es helfen wird.

    – Bleibsee

    7. September 2012 um 14:19 Uhr

  • Es könnte daran liegen, dass Sie versucht haben, eine zu große Datei hochzuladen. Versuchen Sie, eine kleinere Datei hochzuladen. Wenn dies funktioniert, möchten Sie wahrscheinlich die Einstellungen in ändern php.ini damit Sie größere Dateien hochladen können. Wenn Sie dies sehr schnell debuggen möchten, schlage ich vor, dass Sie Folgendes tun var_dump() auf der $_FILES superglobal und sehen Sie, was der Fehlercode des Datei-Uploads ist.

    – Kemal Fadillah

    7. September 2012 um 14:57 Uhr


Ich habe eine Lösung gefunden, die genau so funktioniert, wie ich es möchte.

ich habe mich verändert

$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');

Zu

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

  • Haben Sie die Überprüfung versucht, welcher Dateityp erforderlich ist?

    – kev_m

    15. Juli 2016 um 13:37 Uhr

  • Was ist mit dem Hochladen mehrerer Dateien?

    – jned29

    24. März 2020 um 15:35 Uhr

Benutzeravatar von Chirag Rafaliya
Chirag Rafaliya

CodeIgniter Dateiupload optional …funktioniert einwandfrei….. 🙂

———- Controller ———

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

Ich benutze nur diese Zeilen, was es optional macht,

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

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

Sie können es unnötig machen, indem Sie verwenden $_FILES['userfile']['error'] != 4dann wird dieser Fehler für die erforderliche Datei übergeben und funktioniert hervorragend mit anderen Arten von Fehlern, falls vorhanden, indem verwendet wird falsch zurückgeben hoffe es funktioniert bei dir….

Überprüfen Sie, ob diese Erweiterungsbibliothek für die Formularvalidierung Ihnen beim Validieren von Dateien helfen kann. Wenn Sie das Upload-Feld validieren, wird es mit der aktuellen Formularvalidierung als Eingabefeld behandelt, wenn der Wert leer ist. Sehen Sie sich diese wirklich gute Erweiterung für die Formularvalidierungsbibliothek an

MY_Formvalidation

Sie können die Rückruffunktion wie folgt verwenden

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

Sie können es lösen, indem Sie die Run-Funktion von CI_Form_Validation überschreiben

Kopieren Sie diese Funktion in eine Klasse, die CI_Form_Validation erweitert.

Diese Funktion überschreibt die übergeordnete Klassenfunktion. Hier habe ich nur eine zusätzliche Prüfung hinzugefügt, die auch mit Dateien umgehen kann

/**
 * 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(), "https://stackoverflow.com/") : $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;
}

Benutzeravatar der Community
Gemeinschaft

  1. Legen Sie eine Regel fest, um den Dateinamen zu überprüfen (wenn das Formular mehrteilig ist).

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

  2. überschreibe die $_POST Array wie folgt:

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

  3. und dann mach:

    $this->form_validation->run()

1440790cookie-checkFür den Dateiupload ist eine Validierung in CodeIgniter erforderlich

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy