Question

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?

Was it helpful?

Solution

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)) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top