Search code examples
phpcodeigniterdownloadcodeigniter-2codeigniter-3

Not able to download files kept on server folder in codeigniter


I have few files kept on server folder and their path is stored in database table hwhic looks like this

 Table Name: student_file
    id  name     file
    1   abc     asd/fgh/abc.docx
    2   def     asd/fgh/def.pdf
    3   ghi     asd/fgh/ghi.doc

I have fetched data from the above table(student_file) and displayed in a tabular form where 'download' will be a link or a button that looks like this

abc   download
def   download
ghi   download

Now i want that if user clicks on first download then file of abc should get downloaded and same with 2nd and 3rd.

The code that i have used is downloading the file but when i am trying to open the downloaded file on my system it is saying file not downloaded properly.

View

<a href="<?php echo base_url()?>admin/download/1">Download</a>

Controller

public function download($id)
    {
        $data['download'] = $this->admin_model->get_download_data($id);
    }

Model

public function get_download_data($id)
    {
        $this->db->where('id',$id);
        $data = $this->db->get('student_file');
        $student_data = $data->row();

        $student_file = $student_data->file;
        $ext = substr($student_file, strpos($student_file, ".") + 1);
        $path = 'www.xyz.com/';
        $file = $path . $student_file;
        header("Content-type:application.$ext");
        header("Content-Disposition:attachment;filename='downloaded.$ext");
        readfile($file);
    }

Can anyone please tell how i can download these files properly using codeigniter


Solution

  • I think you can easily do like this,

    <a href="<?php echo base_url(); ?>path/to/file/abc.docx" target="_blank" ></a>
    <a href="<?php echo base_url(); ?>path/to/file/def.pdf" target="_blank" ></a>
    <a href="<?php echo base_url(); ?>path/to/file/ghi.docx" target="_blank" ></a>