Ivanka Todorova
Ivanka Todorova

Reputation: 10219

Check if a file is going to be uploaded? CodeIgniter

I have a form with few inputs and a file input. I want to check whethere the file input is empty or not. If it is empty do not try to upload, if it is not then try to upload it.

I tried something like this:

$upld_file = $this->upload->data();
    if(!empty($upld_file)) 
    {
    //Upload file
    }

Upvotes: 5

Views: 12162

Answers (2)

NDBoost
NDBoost

Reputation: 10634

you use codeigniter's file uploader class... and call $this->upload->do_upload(); in a conditional statement ahd check if its true.

<?php 
if ( ! $this->upload->do_upload()){
    $error = array('error' => $this->upload->display_errors());
    $this->load->view('upload_form', $error);
}
else{
    $data = array('upload_data' => $this->upload->data());
    $this->load->view('upload_success', $data);
}

The user_guide explains this in detail: http://codeigniter.com/user_guide/libraries/file_uploading.html

However, if you are dead set on checking whether a file has been "uploaded" aka.. submitted BEFORE you call this class (not sure why you would). You can access PHPs $_FILES super global.. and use a conditional to check if size is > 0.

http://www.php.net/manual/en/reserved.variables.files.php

Update 2: This is actual working code, i use it on an avatar uploader myself using CI 2.1

<?php
//Just in case you decide to use multiple file uploads for some reason.. 
//if not, take the code within the foreach statement

foreach($_FILES as $files => $filesValue){
    if (!empty($filesValue['name'])){
        if ( ! $this->upload->do_upload()){
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('upload_form', $error);
        }else{
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('upload_success', $data);
        }
    }//nothing chosen, dont run.
}//end foreach

Upvotes: 7

Probably do need more info. But basically, using the codeigniter upload class do something like this:

$result = $this->upload->do_upload();

if($result === FALSE)
{

    // handle error
    $message = $this->upload->display_errors();
}
else
{
    // continue
}

There is a lot of functionality in codeigniter, probably don't need to re-invent the wheel here.

Upvotes: 0

Related Questions