I'm trying to make a PHP page that queries a database, creates a CSV in the tmp folder then sends that csv to the browser to download, but the file that downloads contain only the last echo in the PHP script, not the file that is stored on the server (that file is saved on the server is perfect).
<?php
$db_host = "localhost"; //can be "localhost" for local development
$db_username = "root";
$db_password = "";
$db_name = "seinventory";
$link = mysqli_connect($db_host,$db_username,$db_password,$db_name) or die(mysqli_error($link));
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$softwareName = $_GET['soft'];
$result = mysqli_query($link,"SELECT * FROM `seinventory` WHERE software LIKE '%$softwareName%' or apps LIKE '%$softwareName%'");
$timeStamp = date('d.m.Y-h.i.s');
$csvFile = 'C:/xampp/htdocs/tmp/file.csv';
$new_csv = fopen($csvFile, 'w');
$headings = Array('PC Name','Software Name','Software Version');
fputcsv($new_csv, $headings);
while($row = mysqli_fetch_array($result))
{
$pcName = $row['pcName'];
$software = $row['software'];
$app = $row['apps'];
$softwareArray = explode(";", $software);
$appArray = explode(";", $app);
$multiArray = array_merge($softwareArray, $appArray);
foreach ( $multiArray as $value ) {
$singleSoftwareArray = explode(":", $value);
$softwareItem = $singleSoftwareArray[0];
$pcName = str_replace('.domain.local', '', $pcName);
if (stripos($softwareItem, $softwareName) !== false) {
$singleArray = Array($pcName, $singleSoftwareArray[0], $singleSoftwareArray[1]);
fputcsv($new_csv, $singleArray);
}
}
}
fclose($new_csv);
mysqli_close($link);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="file.csv";');
//unlink($csvFile);
echo "<script>window.close();</script>";
I read somewhere I'm supposed to put exit; after the fclose to stop it writing to the file, but my file on the server is perfect somehow it's being changed during the download process.