Search code examples
phpcodeignitercsv

How to download a text file on link click in codeigniter


I have text file contains Sample of CSV file format, I want my users can download that file on a link click.

This file resides in this folder stucture:

assets->csv->Sample-CSV-Format.txt

This is the code that I have tried to far:

<?php
   $file_name = "Sample-CSV-Format.txt";

   // extracting the extension:
   $ext = substr($file_name, strpos($file_name,'.') + 1);

   header('Content-disposition: attachment; filename=' . $file_name);

   if (strtolower($ext) == "txt") {
       // works for txt only
       header('Content-type: text/plain');
   } else {
      // works for all 
      header('Content-type: application/' . $ext);extensions except txt
   }
   readfile($decrypted_file_path);
?>
 <p class="text-center">Download the Sample file <a href="<?php echo base_url();?>assets/csv/Sample-CSV-Format.txt">HERE</a> It has a sample of one entry</p>

This code is downloading the file on page load instead of link click. Also, it is downloading the whole html structure of the page I want only the text what I have written in text file.

Please guide where is the issue?


Solution

  • You can do it like this, it won't redirect you and also works good for larger files.

    In your controller "Controller.php"

    function downloadFile(){
            $yourFile = "Sample-CSV-Format.txt";
            $file = @fopen($yourFile, "rb");
    
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=TheNameYouWant.txt');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($yourFile));
            while (!feof($file)) {
                print(@fread($file, 1024 * 8));
                ob_flush();
                flush();
            }
    }
    

    In your view "view.php"

    <a href="<?=base_url("Controller/downloadFile")?>">Download</a>