• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
File upload validation

#1
[eluser]macleodjb[/eluser]
Hi guys,

I was wondering how can you use the form validation or any kind of validation with file uploads. I'm trying to create an upload form and i don't want to kill myself with script i'd rather use callbacks. Any suggestions?

#2
[eluser]pistolPete[/eluser]
Say we have a form which consists of a input field (called "image_title") and one file upload.
Both of them are required to pass the validation.

The rule looks like:
Code:
$this->form_validation->set_rules('image_title', 'Image title', 'trim|required|callback__do_upload');
Code:
// callback function to process the file upload and validate it
function _do_upload($file)
{
    $config['upload_path'] = './folder/';
    $config['allowed_types'] = 'put|your|allowed|types|here';
    $this->load->library('upload', $config);
        
    if ( ! $this->upload->do_upload())
    {
        // set the validation error using the errors provided by the upload class
        $this->form_validation->set_message('_do_upload', $this->upload->display_errors());
        return FALSE;
    }    
    else
    {
        return TRUE;
    }
}

#3
[eluser]macleodjb[/eluser]
I'm working on a file upload script but it's crapping out somewhere i can't figure out where, I seem to have a problem with getting my error messages to show up when something fails, this worked fine before integrating with CI.

I have all of this code inside the controller.
Code:
<?php
class File extends Controller {

    function File()
    {
        parent::Controller();
        session_start();
    }
    
    function index() {
        redirect('dashboard');        
    }// end of function
    
    function add_file_to_job() {
        //$this->load->model('File_model');
        $this->load->model('Main_model');
        $this->load->library('form_validation');    

        $this->form_validation->set_rules('user_file', 'File', 'required');        

        $job_id = $this->uri->segment(3);
        if ($this->form_validation->run() == FALSE){
            $this->load->view('file/upload_form', $data);
        } else {
            $file_types = array('pdf', 'zip');
            $max_size = '4096';
            $path = 'files/job/';
            if($this->upload_file($file_types, $max_size, $path, $job_id)){
            $this->load->view('file/upload_success', $data);
            } else {
            $data['error'] = "There was an internal error, you file was not saved, Please contact support";
            $this->load->view('file/upload_form', $data);
            }
        }
        
    }// end of function
    
    
    function checkFileProperties($file_types, $max_size) {
        $file_basename = strtolower(basename($_FILES['user_file']['name']));
        if($this->checkFileExt($file_basename,$file_types)) {
            if($this->checkFileSize($file_basename,$max_size)) {
            return true;
            } else {//else for check file size
            return false;
            }
        } else {//else for check file ext
        return false;
        }
    }
    
    function createFileName($extension,$user_id) {
        $random = mt_rand();
        $newfilename = $user_id . $random . "." . $extension;
        return $newfilename;
    }
    
    function SaveFileToDB($uid, $name, $oldname, $path, $job_id = '', $profile_photo = '', $company_photo = '', $portfolio_photo = '') {
      $save_query = $this->db->query("INSERT INTO files (job_id, file_name, old_filename, user_id, path, company_photo, portfolio_photo, profile_photo) VALUES ('".$job_id."', '".$name."', '".$oldname."', '".$uid."', '".$path."', '".$company_photo."', '".$portfolio_photo."', '".$profile_photo."' )");
    $saved = $this->db->affected_rows($save_query);
        if($saved > 0){
        return true;
        } else {
        return false;
        }
    }
    function uploadFile($file_types, $max_size, $path, $job_id) {
        if($this->checkFileProperties($file_types, $max_size)) {
            $extension = end(explode('.', strtolower(basename($_FILES['user_file']['name']))));
            $name = $this->createFileName($extension,$_SESSION['uid']);
            $newfilename = $path . $name;
            move_uploaded_file($_FILES['user_file']['tmp_name'], $newfilename);
            @chmod($newfilename, 0644);
            $oldname = basename($_FILES['user_file']['name']);
            if($this->SaveFileToDB($_SESSION['uid'], $name, $oldname, $path, $job_id)){
            return true;
            } else {
            return $error = "ERROR: We had some trouble saving your file to the database, please contact support";
            //return false;
            }
        } else {
        $error = "ERROR: The file you are trying to upload has invalid properties, Please check the file requirements on this page";
        }
    }
    
    function checkFileExt($filename,$file_types) {
    $extension = end(explode('.', $filename));
        if(in_array($extension,$file_types)) {
        return true;
        } else {
        return false;
        }
    }
    
    function checkFileSize($filename,$max_size) {
    $filesize = @filesize($filename);
        if($filesize < $max_size) {
        return true;
        } else {
        return false;
        }
    }

    
    
}?&gt;

#4
[eluser]macleodjb[/eluser]
I removed the form validation from my script and it worked fine. My question is now, why does the form validation error? Everything i'm looking at seems to be good. What am i missing?

#5
[eluser]pistolPete[/eluser]
I didn't see a problem directly, but I have some advices for you, which could clean up your code:

I'd recommend using the file uploading class, no need to reinvent the wheel.

And I really would use a callback function for validating your file upload, just like I pointed out above.

One last thing: Use models to separate your database logic!

#6
[eluser]macleodjb[/eluser]
I didn't think i could use a callback because i need to pass extra parameters through the function. The way it is written now i can use this same page in multiple locations each with different criteria for the file type and size. but if you can pass vars through a callback please show me, i'm interested in learning.

#7
[eluser]pistolPete[/eluser]
Have a look at this thread: http://ellislab.com/forums/viewthread/105171/

Btw: you could also use class variables to store extra parameters!

#8
[eluser]macleodjb[/eluser]
i don't think that will work for my situation. If you could pass extra params then i would do that.

I would like to know why the form validation does not work with files? Whenever i don't comment out the validation rule the script works fine. What gives?

Here's my validation rule
Code:
$this->form_validation->set_rules('user_file', 'File', 'required');

and here is what i have in my form.
Code:
&lt;input type="file" name="user_file" size="20" /&gt;

#9
[eluser]mindesign[/eluser]
[quote author="pistolPete" date="1235453832"]Say we have a form which consists of a input field (called "image_title") and one file upload.
Both of them are required to pass the validation.

The rule looks like:
Code:
$this->form_validation->set_rules('image_title', 'Image title', 'trim|required|callback__do_upload');
Code:
// callback function to process the file upload and validate it
function _do_upload($file)
{
    $config['upload_path'] = './folder/';
    $config['allowed_types'] = 'put|your|allowed|types|here';
    $this->load->library('upload', $config);
        
    if ( ! $this->upload->do_upload())
    {
        // set the validation error using the errors provided by the upload class
        $this->form_validation->set_message('_do_upload', $this->upload->display_errors());
        return FALSE;
    }    
    else
    {
        return TRUE;
    }
}
[/quote]

Hey there. i'm trying to implement what you posted here but i'm running into problems....absolutely nothing happens, no errors, nothin.

I set my rule like so
Code:
$this->form_validation->set_rules('image', 'Image', 'required|callback__do_upload');

and your callback function like so. I added in 'image' into the do_upload thinking that might be the problem...but alas i guess it's not.
Code:
function _do_upload($file)
    {
        $config['upload_path'] = './public/images/temp_images/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $this->load->library('upload', $config);
            
        if ( ! $this->upload->do_upload('image'))
        {
            // set the validation error using the errors provided by the upload class
            $this->form_validation->set_message('_do_upload', $this->upload->display_errors());
            return FALSE;
        }    
        else
        {
            return TRUE;
        }
    }

any help greatly appreciated!!

grant

#10
[eluser]pistolPete[/eluser]
Quote:I added in ‘image’ into the do_upload

How is the file upload field in the view called?

Quote:absolutely nothing happens, no errors, nothin.
Enable error logging & displaying.

Post your full controller and view code please.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.