Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
like image 539
Ivanka Todorova Avatar asked Feb 14 '12 12:02

Ivanka Todorova


1 Answers

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
like image 55
NDBoost Avatar answered Sep 28 '22 05:09

NDBoost