Codeigniter中的文件上载验证

时间:2017-08-06 17:26:53

标签: php validation file-upload codeigniter-3

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

图片上传阵列:

array(
            'field'=>'image',
            'label' => 'Image',
            'rules' => 'required'
        )

当我尝试上传图片时,它没有响应,就像它是必需的等等。我也想验证它为.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);

        }
    }

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

7 个答案:

答案 0 :(得分:4)

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

控制器: Front.php

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

}

查看: 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>

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

在上面的示例中,我首先验证了nameemail,而对于Image我正在调用validate_image函数来验证它,因为form_validation库不提供图像验证但是我有回调来进行自定义验证,validate_image将检查图像内容类型,然后检查图像文件大小,然后检查图像扩展,如果未满足任何这些要求,它将使用set_message()为每个要求设置错误消息form_validation库的功能。

答案 1 :(得分:3)

目前您没有收到错误,因为您设置了验证规则,您还初始化了配置,但在上传课程后,您没有检查是上传文件还是错误。

请检查下面提到的解决方案,它将帮助您解决此问题。

更新1:

要调用特定组,您将其名称传递给$this->form_validation->run('task')方法。我在代码中看不到任何$config['task']数组。请检查我下面提到的代码并根据您的inputs更新。

public function Task() {

    $config = array(
        'task' => array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'required'
            ),
            array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'required'
            )
    ));
    $this->load->library('form_validation');
    if ($this->form_validation->run('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 {
        $fconfig['upload_path'] = './taskimages/';
        $fconfig['allowed_types'] = 'gif|jpg|png';
        $fconfig['max_size'] = '10048';
        $fconfig['overwrite'] = FALSE;

        $this->load->library('upload', $fconfig); //Load the upload CI library
        $this->load->initialize($fconfig);

        if (!$this->upload->do_upload('my_image')) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('form' ,$error);
        } else {
            $file_info = $this->upload->data();
            $file_name = $file_info['my_image'];
            $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);

            $data['upload_data'] = array('upload_data' => $this->upload->data());
            $this->load->view('YOUR_SUCCESS_VIEW PAGE', $data);
        }
    }
}

如果不起作用,请告诉我。

答案 2 :(得分:2)

来自CI的File Uploading Class怎么样?

课程也提供验证:

$config['allowed_types']        = 'gif|jpg|png';
$config['max_size']             = 100;
$config['max_width']            = 1024;
$config['max_height']           = 768;

该链接包括上传表单,成功页面和控制器。

按照那里的指示,你永远不会迷路。

答案 3 :(得分:2)

我正在使用此代码进行多个图片上传。 现在尝试下面的代码,希望它会有所帮助。

 public function __construct(){
        parent::__construct();

        $this->load->helper('date');
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->helper('html');
        $this->load->library('form_validation');
        $this->load->library('email');
        $this->form_validation->set_error_delimiters('', '');
        $config['allowed_types'] = 'jpeg|jpg|png|bmp';
        $this->load->library('upload', $config);
        $this->load->library('session');

    }



 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 {

            $filesCount = count($_FILES['file']['name']);
            $result     = '';
            if($filesCount > 0) {
                $event_id     = trim($this->input->post('event_name'));
                for($i = 0; $i < $filesCount; $i++) {

                    $_FILES['gallery']['name']      = $_FILES['file']['name'][$i];
                    $_FILES['gallery']['type']      = $_FILES['file']['type'][$i];
                    $_FILES['gallery']['tmp_name']  = $_FILES['file']['tmp_name'][$i];
                    $_FILES['gallery']['error']     = $_FILES['file']['error'][$i];
                    $_FILES['gallery']['size']      = $_FILES['file']['size'][$i];

                    $image = $_FILES['gallery']['name'];
                    $directoryPath = date('Y/M/');

                    $path_info = pathinfo($image);
                    //check file type valid or not
                    if(in_array($path_info['extension'], array('jpg', 'jpeg','png', 'gif','JPG','JPEG'))){
                        // Upload job picture
                        $random = time();
                        $config['upload_path']   = './taskimages/';
                        $config['allowed_types'] = 'jpg|png|jpeg|bmp';
                        $config['file_name']     = $random;
                        $config['encrypt_name']  = TRUE;
                        $config['max_size']      = '250000000';
                        $config['max_width']     = '75000000';
                        $config['max_height']    = '7500000';

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

                        ini_set('upload_max_filesize', '10M');
                        ini_set('memory_limit', '-1');

                        if ($this->upload->do_upload('gallery')) {

                            $imageArray = $this->upload->data();
                            $image_name = $imageArray['raw_name'] . '' . $imageArray['file_ext']; // Job Attachment

                            $config1['image_library'] = 'gd2';
                            $config1['source_image'] = './taskimages/' . $image_name;
                            $config1['create_thumb'] = TRUE;
                            $config1['maintain_ratio'] = TRUE;
                            $config1['width'] = 620;
                            $config1['height'] = 540;

                            $this->load->library('image_lib', $config);
                            $this->image_lib->initialize($config1);
                            $this->image_lib->resize();
                            $this->image_lib->clear();


                            $file_name = $image_name_thumb = $imageArray['raw_name'] . '_thumb' . $imageArray['file_ext'];
                            $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);
                        }
                    }
                }
            }
        }
    }

答案 4 :(得分:2)

这里我只写上传样本文件。根据您的要求进行更改。 的控制器/ Files.php

const { URL } = require('url');
const myUrl = new URL('http://example.com');
const myUrlString = myUrl.toString();

查看/ upload_view.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Files extends CI_Controller {

function __construct() {
    parent::__construct();
}

public function upload(){
    $data = array();

    $this->load->library('form_validation');
    $this->load->helper('file');

    $this->form_validation->set_rules('task', '', 'callback_file_check');

    if($this->form_validation->run() == true){
        //upload configuration
        $config['upload_path']   = 'uploads/files/';
        $config['allowed_types'] = 'gif|jpg|png|pdf';
        $config['max_size']      = 1024;
        $this->load->library('upload', $config);
        //upload file to directory
        if($this->upload->do_upload('task')){
            //YOU CAN DO WHAT DO THE PROCESS
        }else{
            $data['error_msg'] = $this->upload->display_errors();
        }
    }        
    //load the view
    $this->load->view('upload_view', $data);
}

public function file_check($str){
    $allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/pjpeg','image/png','image/x-png'); //HERE you CAN GIVE VALID FILE EXTENSION
    $mime = get_mime_by_extension($_FILES['task']['name']);
    if(isset($_FILES['task']['name']) && $_FILES['task']['name']!=""){
        if(in_array($mime, $allowed_mime_type_arr)){
            return true;
        }else{
            $this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
            return false;
        }
    }else{
        $this->form_validation->set_message('file_check', 'Please choose a file to upload.');
        return false;
    }
}
}
?>

答案 5 :(得分:2)

在CODEIGNITER 4中,Validation类包含文件验证功能。您可以通过以下代码块实现它。

在Config / Validation.php中添加

public $signup = [
        'username' => [
            'rules'  => 'required|alpha',
            'errors' => [
                'required' => 'You must choose a Username.'
            ]
        ],
        'profile_image' => [
            'rules' => 'uploaded[profile_image]|max_size[profile_image,1024]|ext_in[profile_image,png,jpg]|max_dims[profile_image,1000,1000]',
            'label' => 'profile image'
        ]
    ];

在您的控制器中添加以下代码

public function register()
{
    $validation =  \Config\Services::validation();
    if($this->request->getMethod() == 'post') {
        //$validation->setRuleGroup('signup');
        if (!$this->validate('signup')) {
            //$validationErrors = $validation->getErrors();
            echo view('register', [
                'validation' => $validation
            ]);
        }
        else
        {
            // your logic goes here....
            echo view('Success');
        }
    } else {
        echo view('register', [
            'validation' => $validation
        ]);
    }
}

您的视图会像

    <?= $validation->listErrors() ?>
<?php echo form_open_multipart(); ?>
<div class="row">
    <div class="col-md-4 offset-md-4">
        <label>Full Name</label><br/>
        <input type="text" name="username" class="form-control" size="50" value="<?php echo set_value('username'); ?>"/>
    </div>
</div>
<div class="row">
    <div class="col-md-4 offset-md-4">
        <label>Profile Picture</label><br/>
        <input type="file" name="profile_image" class="form-control" value="<?= set_value('profile_image') ?>"/>
    </div>
</div>
<div class="row">
    <div class="col-md-4 offset-md-4"><br/>
        <button class="btn btn-primary btn-block">Login</button>
    </div>
</div>
<?php echo form_close(); ?>

答案 6 :(得分:1)

您没有使用CI上传类收到错误,因为您没有调用它的错误方法。更改您的更新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);
        if ( ! $this->upload->do_upload('task'))
        {       
                $upload_error = $this->upload->display_errors(); //Here you will get errors. You can handle with your own way
                echo $upload_error; //<------------you can echo it for debugging purpose
                $data['error'] = $upload_error; //<-------------you can send it in view to display error in view.
                $this->load->view('your_view' ,$data); //<---pass data to view
        }
        else
        {
            $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);
        }



    }
}

在视图中

echo (isset($error))?$error:"";