Search code examples
phpcodeigniterdownloadwritefileforce-download

How to Choose the location to save the download files when forcing file download in Codeigniter?


Now, the CSV file is exported in reports folder. Instead i want the browser to ask where to export the file. so that i can export the file in desired location of client machine and avoid storing those files in server (i.e)reports folder.

$this->load->dbutil();    
$this->load->helper('file');
$this->load->helper('download');

$selProducts= $this->db->query("SELECT * FROM tablename");
$data= $this->dbutil->csv_from_result($selProducts);
$randomidgenerated = "reports/".date('Y-m-d').".csv";

if(file_exists(FCPATH.$randomidgenerated)){
        $randomidgenerated = "reports/".date('Y-m-d')."_".random_string('alnum', 3).".csv";
    }

if ( ! write_file($randomidgenerated, $data))
{
     echo 'Unable to write the file';        
}    

$data = file_get_contents($randomidgenerated);
force_download($randomidgenerated, $data, TRUE);

Solution

  • from what i can see you are just creating the contents of the file to be downloaded dynamically... What you have to do now is force the browser to download the file to the clients chosen part then probably delete the temporary file afterwards if you dont want to store it on the server... Add the code below just after you have created the file or sure of its existence... something like

    $file = FCPATH.$randomidgenerated;          
    if(file_exists($file)){
                    header('Content-Description: File Transfer');
                    header('Content-Type: text/csv');
                    header('Content-Disposition: attachment; filename='.basename($file));
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($file));
                    ob_clean();
                    flush();
                    readfile($file);
    
                    exit;
    }
    

    That should do it.