Home > Blockchain >  Prevent CSV file downloading (CodeIgnitor)
Prevent CSV file downloading (CodeIgnitor)

Time:01-31

I need to create csv and then send it to mail as attachment. I am using headers which is getting me downloaded the csv file. and if I remove the below then no CSV is created.

header('Content-Type: text/csv');

I dont want to download the file instead save it in some temp folder and then send it as attachment in mail.

below is what i did..

$this->load->library('excel');
    $filename = tempnam(sys_get_temp_dir(), 'export') . '.csv';
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename="'.$filename.'"');
  //$f = fopen('php://output', 'w');
    $f = fopen($filename, 'w');
    $csv_header =  array("name","number","address"); 
    fputcsv($f, $csv_header);
    ob_flush();
    flush();
    foreach ($data as $value) {
            $data_array = array($value['name'],$value['number'],$value['address']);
            fputcsv($f, $data_array);
            }
        }
    fclose($f);

CodePudding user response:

Solution

Remove these header lines as they are used to download files to a browser.

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="'.$filename.'"');

On the serverside, you should be good with just

$this->load->library('excel');
$temporary_filename = tempnam(sys_get_temp_dir(), 'export') . '.csv';
    
$file_write_stream = fopen($temporary_filename, 'w');
$csv_header =  array("name","number","address"); 
fputcsv($file_write_stream, $csv_header);
    
foreach ($data as $value) {
    fputcsv($file_write_stream, array($value['name'], $value['number'], $value['address']));
}

fclose($file_write_stream);

Pro tips:

  1. Use meaningful variable names
  2. For sending the email, I'd recommend using the PHP mailer library. It makes sending email super simple and you can add an attachment with just one line. In your case:
$mail->addAttachment($temporary_filename);
  • Related