0

I am trying to upload an Excel file in my upload directory. It is running when I am not checking the file extension. But when I check the file extension, it displays an invalid file all the time.

My code is given below:

function upload_attendance(){
    $config['upload_path'] = './uploads/';
    $this->load->library('upload', $config);
    $allowedExts = array("xls");
    $temp = explode(".",$_FILES["file"]["name"]);
    $extension = end($temp);
    if(($_FILES["file"]["type"]=="file/xls")&&in_array($extension,$allowedExts)){
        if($FILES["file"]["error"]>0){
            $data['msg'] = $this->upload->display_errors();
            $data['sign'] = 'error_box';
            $this->session->set_userdata($data);
                redirect('attendance/add_attendance');;
        }
        else{
            echo "Uploaded.";
        }
    }
    else{
        $data['msg'] = "Invalid file type.Try to upload a valid file.";
        $data['sign'] = 'error_box';
        $this->session->set_userdata($data);
            redirect('attendance/add_attendance');
    }
}

How can I check the file extension before uploading? Could you help me?

nbanic
  • 1,270
  • 1
  • 8
  • 11
user3617840
  • 67
  • 2
  • 10

1 Answers1

1

In this line

if(($_FILES["file"]["type"]=="file/xls")&&in_array($extension,$allowedExts)){

you're checking that both extension AND mime type are right, but AFAIK excel MIME isn't file/xls -> I don't know where you came up with that.

According to this resource the mime types for Excel file should be:

xls   application/vnd.ms-excel
xlt   application/vnd.ms-excel
xla   application/vnd.ms-excel
xlsx  application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xltx  application/vnd.openxmlformats-officedocument.spreadsheetml.template
xlsm  application/vnd.ms-excel.sheet.macroEnabled.12
xltm  application/vnd.ms-excel.template.macroEnabled.12
xlam  application/vnd.ms-excel.addin.macroEnabled.12
xlsb  application/vnd.ms-excel.sheet.binary.macroEnabled.12

Likely you can come out wiht just the two most used, so application/vnd.ms-excel and application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (for > 2007 documents).

This should work:

$mimes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
$allowedExts = ['xls', 'xlsx'];
if (in_array($_FILES['file']['type'], $mimes) && in_array($extension, $allowedExts)) {
Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
  • Exactly, You are right.But If I want to add mimes to codeigniter mime then how to change this code without $mimes here. Is it possible? – user3617840 May 11 '14 at 08:03
  • 1
    Yes, just add the new mimes inside the `application/config/mimes.php` file and CI should pick them up from there – Damien Pirsy May 11 '14 at 08:05