How to load a text file by click link in codeigniter

I have a text file containing a sample CSV format, I want my users to be able to download this file from the link.

This file is located in this folder:

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

This is the code I've tried so 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 loads the file when the page loads, instead of the link. It also loads the entire structure of the html page. I want only the text that I wrote in the text file.

Indicate where the problem is?

+4
source share
4 answers

You can do it like this, it will not redirect you, and also works great for large 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 opinion "view.php"

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

You can do this simply by loading the HTML5 atrribute. Just add this line to your download link.

 <a href="<?php echo base_url();?>assets/csv/Sample-CSV-Format.txt" download="Sample-CSV-Format.txt"> HERE </a> 
+5
source

do this:

someother_file.php

 <?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") { header('Content-type: text/plain'); // works for txt only } else { header('Content-type: application/'.$ext); // works for all extensions except txt } readfile($decrypted_file_path); ?> 

some_html_page.html

  <p class="text-center">Download the Sample file <a href="<?php echo base_url();?>/someother_file.php">HERE</a> It has a sample of one entry</p> 
0
source

In my opinion, it is better to have a client-side download code than to have a controller method written for this. you can use this link

0
source

All Articles