0

i have this code that work for me on other projects but now instead to download the file is show the file on browser

$query = "SELECT * FROM leads";
$result = $dbconn->query($query);

$filename = "leads_shaldor_" . date("Y-m-d H:i");
$filepath = "/var/www/vhosts/as7.co.il/shaldor.as7.co.il/exports/" 
.$filename. ".csv";
    $downpath = "http://shaldor.as7.co.il/exports/" .$filename. ".csv";
    $csvFile = fopen($filepath, 'w') or die("can't open file");
    fprintf($csvFile, chr(0xEF).chr(0xBB).chr(0xBF));
    while($row = $result->fetch_assoc()){
        fputcsv($csvFile, 
array($row['id'],$row['name'],$row['phone'],$row['date']));
        print_r($row);
    }
    fclose($csvFile);
    header("Location: " . $downpath);


$result->close();
$sql->close();

3 Answers3

0
$downpath = "http://shaldor.as7.co.il/exports/" .$filename. ".csv";
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($downpath) . "\"")

Set the following headers. It should force a download. Your browser is opening it because it knows how to render the file.

Toby Okeke
  • 624
  • 3
  • 13
0

refer to this answer:Forcing to download a file using PHP

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
-1

You can use This.

To brute force all CSV files on your server to download, add in your .htaccess file:

AddType application/octet-stream csv

PHP Solution

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
Coder
  • 11
  • 1
  • 6