在Codeigniter中的文件上传验证 [英] File Upload Validation In Codeigniter

查看:121
本文介绍了在Codeigniter中的文件上传验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图验证文件上传的图像上传,但它没有得到像其他领域的验证。
$ b

图像上传数组:

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

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

我检查了很多问题,并尝试使用call方法,但是无法修复它。 请提供详细的答案用代码示例。请在示例中使用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'] =添加新任务;
$ 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/'; //保存图片的路径
$ config ['allowed_types'] ='gif | jpg | png'; //接受的图片扩展
$ config ['max_size'] ='10048'; // kb的
// $ config ['max_width'] ='1024'; // px
// $ config ['max_height'] ='768'的图片宽度的最大值; //图像高度的最大值px
$ config ['overwrite'] = FALSE; //如果存在一个具有相同名称的图像,它将被覆盖。如果不想覆盖
$ this-> load->库('upload',$ config),则设置为false。 //加载上传CI库
$ 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->输入 - > post('jnature'),
'Assignee'=> $ this-> input-> post('assigne'),
'Employee_Name'=> $ this- ('ddate'),
'Reminder'=> $ ('提醒'),
'Task_Image'=> $ file_name,
);

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


$ b $ / code $ / pre

我已经在使用CI的上传类,但它不工作,现在我想验证图像/文件从form_validation方。

解决方案

<我为你的问题写了一个完整的例子,我希望这会有所帮助。在以下代码中,我使用了CI的表单验证回调和表单验证自定义错误消息。
$ b 控制器:Front.php





class Front扩展了CI_Controller {b / b>

  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'您表格已成功提交';



public function validate_image(){
$ check = TRUE;
if((!isset($ _ FILES ['my_image']))|| $ _FILES ['my_image'] ['size'] == 0){
$ this-> form_validation-> ; set_message('validate_image','{field} field is required');
$ check = FALSE;

else if(isset($ _ FILES ['my_image'])&& $ _FILES ['my_image'] ['size']!= 0){
$ allowedExts =数组(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', '图片文件大小不能超过20MB!');
$ check = FALSE;
}
if(!in_array($ extension,$ allowedExts)){
$ this-> form_validation-> set_message('validate_image',Invalid file extension {$ extension} );
$ check = FALSE;
}
}
return $ check;

code










$ b $ p


$ b

View: form.php

 <!DOCTYPE html> 
< html>
< head>
< title>图片上传< /标题>
< / head>
< body>
< h1>< a href =<?= base_url()?>>表格< / a>< / h1>
<?php if(!empty(validation_errors())):?>
< p><?= validation_errors()?>< / p>
<?php endif; ?>
<?= form_open('front / upload_image',['enctype'=>'multipart / form-data])?>>
< label>名称:< / label>< input type =textname =namevalue =<?= set_value('name')?>><标签>
< label>电子邮件:< / label>< input type =emailname =emailvalue =<?= set_value('email')?>><< ; /标签>
< input type =filename =my_image>
< button type =submit>提交< / button>
<?= form_close()?>
< / body>
< / html>

form_validation.php


$ b $

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


);

在上面的示例中,首先验证名称电子邮件和图像我调用 validate_image 函数来验证它,因为form_validation库不提供图像验证,但我有回调做自定义验证, validate_image 将检查图像内容类型,然后检查图像文件大小,然后检查图像扩展如果任何这些要求不满足使用 set_message()函数为 form_validation 库设置每个需求的错误消息。

I am trying to validate file upload for image uploading, but it is not getting the validation like other fields. I am using Form_Validation.php process for validation.

Image uploading array:

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

when i try to upload the image it did not response like it is required etc. I also want to validate it for .jpg etc and "how to set the file value on incorrect file like instead of .jpg we try to upload the .pdf" like we set the value of input field set_value('field name') etc.

I checked a lot of questions and also try to use call method, but did not able to fix it.

UPDATE:

Please provide detail answer with code example. Please use the form_validation.php way in example and also provide the callback example code, so i can read / learn and modify it accordingly.

UPDATE 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);

        }
    }

I am already using CI uploading class but it is not working, and now i want to validate the image/ file from form_validation side.

解决方案

I wrote a complete example for your problem, I hope it will help. In the following code I am using CI's Form validation callback and Form Validation Custom Error Messages.

Controller: Front.php

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

}

View: 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'
                )
        )
);

In above example first I am validating the name and email and for the Image I am calling the validate_image function to validate it, since form_validation library does not provide image validation but i has callbacks to do custom validations, the validate_image will check image content type then check image file size and then check image extension if any of these requirements are not fulfilled it will set error message for each requirement using set_message() function of form_validation library.

这篇关于在Codeigniter中的文件上传验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆