phpcodeigniter

Provide Download path for files in Codeigniter


The thing in a table there are some checkboxes so based on the checkboxes user have checked it will download a particular column of the table in .php format.

I have tried the following code:

public function export_php() {
            $export = $this->session->userdata('export_id');
            $exports = $this->query_revision_model->export($export);
            $data = "";

            foreach ($exports as $export) {
                $data .= $export->sql_changes . "\r\n";
            }

            $filename = "export.php";
            $handle = fopen($filename, w);
            fwrite($handle, $data);
            fclose($handle);
}

Everything is working fine, but I'm unable to provide the path for the download files, so it's saving in the application folder which I don't want.

I tried force_download($filename, $data) but that didn't work because I am using Ajax.


Solution

  • You need to force the browser to download file except display.

    public function export_php() {
            $export = $this->session->userdata('export_id');
            $exports = $this->query_revision_model->export($export);
            $data = "";
            foreach ($exports as $export) {
                $data .= $export->sql_changes . "\r\n";
            }
            $filename = "export.php";
            $handle = fopen($filename, w);
            fwrite($handle, $data);
            fclose($handle);
            $filePath = APPPATH.$fileName;
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=$fileName");
            header("Content-Type: application/php");
    
    // Read the file
    readfile($filePath);
    exit;
    }
    

    and in your ajax code try this instead of ajax

    window.location.replace('Your URL Here')
    

    Hope it helps!