ryanpitts1
ryanpitts1

Reputation: 894

PHP Content-Disposition: attachment works locally but not on server

What i am doing is querying the database to build a CSV file. I am using these headers to save the file:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="export.csv"');

It's is working locally on my WAMP setup but not on the server. Is there a setting or something in PHP or Apache that i need to change to allow for this?

When i click the link locally it downloads a CSV file. When i do the same thing on the live server it just brings me to the php page that is generating the CSV content.

Upvotes: 0

Views: 2406

Answers (2)

Pranav Sangave
Pranav Sangave

Reputation: 21

I faced the same problem as you. In my case, the solution is that we just have to use include 'connection_file.php'; after

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

Means your header files must be the first statement of the file.

Complete PHP code to export csv is :

<?php

if(isset($_POST['Export'])){

      header('Content-Type: text/csv; charset=utf-8');
      header('Content-Disposition: attachment; filename=data.csv');

      include '../dbcon.php';

      $output = fopen("php://output", "w");
      fputcsv($output, array('id', 'name', 'phone', 'Employee Name', 'district', 'taluka', 'address'));
      $query = "SELECT * from export_buffer ORDER BY id DESC";
      $result = mysqli_query($con, $query);
      while($row = mysqli_fetch_assoc($result))
      {
           fputcsv($output, $row);
      }
      fclose($output);
 }
?>

Upvotes: 0

Joe
Joe

Reputation: 47649

Try using application/octet-stream not text/csv. I don't know why your browser behaves differently for different domains, but it is more common to use application/octet-stream. This is mentioned in RFC2616. As you're not displaying it in the browser, the content-type doesn't have to match the content anyway.

Upvotes: 1

Related Questions