Codeigniter中的文件上载验证

msz*_*msz 7 php validation file-upload codeigniter-3

我正在尝试验证文件上传以进行图像上传,但它没有像其他字段那样获得验证.我正在使用Form_Validation.php流程进行验证.

图片上传阵列:

array(
            'field'=>'image',
            'label' => 'Image',
            'rules' => 'required'
        )
Run Code Online (Sandbox Code Playgroud)

当我尝试上传图片时,它没有响应,就像它是必需的等等.我也想验证它.jpg等"和如何设置文件值在不正确的文件上,而不是.jpg我们尝试上传.pdf"像我们设置的值输入字段set_value('field name')

我检查了很多问题,并尝试使用调用方法,但无法修复它.

更新:

请通过代码示例提供详细答案.请在示例中使用form_validation.php方式,并提供回调示例代码,以便我可以相应地阅读/学习和修改它.

更新2:

 public function Task()
    {
        if ($this->form_validation->run('Sub_Admin/task') == FALSE) {
            $this->data['Task'] = $this->bm->get_usr();
            $data['title'] = "Add New Task";
            $this->load->view('Subadmin/header',$data);
            $this->load->view('Subadmin/nav');
            $this->load->view('Subadmin/sidebar');
            $this->load->view('Subadmin/task', $this->data);
            $this->load->view('Subadmin/footer');
        }
        else
        {

            $config['upload_path'] = './taskimages/'; //The path where the image will be save
            $config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
            $config['max_size'] ='10048'; //The max size of the image in kb's
            //$config['max_width']  = '1024'; //The max of the images width in px
            //$config['max_height']  = '768'; //The max of the images height in px
            $config['overwrite'] = FALSE; //If exists an image with the same name it will overwrite. Set to false if don't want to overwrite
            $this->load->library('upload', $config); //Load the upload CI library
            $this->load->initialize($config);
            $this->upload->do_upload('task');
            $file_info = $this->upload->data();
            $file_name = $file_info['file_name'];
            $data = array(
                'Job_Title' => $this->input->post('jtitle'),
                'Priority' => $this->input->post('jnature'),
                'Assignee' => $this->input->post('assigne'),
                'Employee_Name' => $this->input->post('assignto'),
                'Due_Date' => $this->input->post('ddate'),
                'Reminder' => $this->input->post('reminder'),
                'Task_Image' => $file_name,
            );

            $this->bm->add_task($data);

        }
    }
Run Code Online (Sandbox Code Playgroud)

我已经在使用CI上传类,但它无法正常工作,现在我想从form_validation端验证图像/文件.

Muh*_*mad 5

我为您的问题写了一个完整的示例,希望对您有所帮助。在下面的代码中,我使用了 CI 的表单验证回调和表单验证自定义错误消息。

控制器: Front.php

类 Front 扩展 CI_Controller {

public function index() {
    $this->load->view('form');
}

public function upload_image() {
    $this->load->library('form_validation');
    if ($this->form_validation->run('user_data') == FALSE) {
        $this->load->view('form');
    }
    else {
        echo 'You form Submitted Successfully ';
    }
}

public function validate_image() {
    $check = TRUE;
    if ((!isset($_FILES['my_image'])) || $_FILES['my_image']['size'] == 0) {
        $this->form_validation->set_message('validate_image', 'The {field} field is required');
        $check = FALSE;
    }
    else if (isset($_FILES['my_image']) && $_FILES['my_image']['size'] != 0) {
        $allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "GIF", "PNG");
        $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
        $extension = pathinfo($_FILES["my_image"]["name"], PATHINFO_EXTENSION);
        $detectedType = exif_imagetype($_FILES['my_image']['tmp_name']);
        $type = $_FILES['my_image']['type'];
        if (!in_array($detectedType, $allowedTypes)) {
            $this->form_validation->set_message('validate_image', 'Invalid Image Content!');
            $check = FALSE;
        }
        if(filesize($_FILES['my_image']['tmp_name']) > 2000000) {
            $this->form_validation->set_message('validate_image', 'The Image file size shoud not exceed 20MB!');
            $check = FALSE;
        }
        if(!in_array($extension, $allowedExts)) {
            $this->form_validation->set_message('validate_image', "Invalid file extension {$extension}");
            $check = FALSE;
        }
    }
    return $check;
}
Run Code Online (Sandbox Code Playgroud)

}

查看: form.php

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload</title>
</head>
<body>
    <h1><a href="<?= base_url() ?>">Form</a></h1>
    <?php if(!empty(validation_errors())): ?>
        <p><?= validation_errors() ?></p>
    <?php endif; ?>
    <?= form_open('front/upload_image', ['enctype' => "multipart/form-data"]) ?>
    <label>Name: </label><input type="text" name="name" value="<?= set_value('name') ?>"></label>
    <label>E-mail: </label><input type="email" name="email" value="<?= set_value('email') ?>"></label>
    <input type="file" name="my_image">
    <button type="submit">Submit</button>
    <?= form_close() ?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

form_validation.php

$config = array(
        'user_data' => array(
                array(
                        'field' => 'name',
                        'label' => 'Name',
                        'rules' => 'trim|required'
                ),
                array(
                        'field' => 'email',
                        'label' => 'Email',
                        'rules' => 'trim|required|valid_email'
                ),
                array(
                        'field' => 'my_image',
                        'label' => 'Image',
                        'rules' => 'callback_validate_image'
                )
        )
);
Run Code Online (Sandbox Code Playgroud)

在上面的例子中第一,我验证nameemail和图像,我调用validate_image函数来验证它,因为form_validation库不提供图像验证,但我有回调做定制验证时,validate_image将检查图像的内容类型,然后检查图像文件大小然后检查图像扩展,如果没有满足这些要求中的任何一个,它将使用库的set_message()功能为每个要求设置错误消息form_validation