0

I am trying to write a table from my sql database to a CSV file and make the user download it. However the file that is downloaded is full of html data from the site the form is on. After 80 lines of html code my own data is shown. The only thing i can think of is some sort of buffer overflow but I do not understand why.

This is my code:

if (!empty($_POST['inschrijvingen']) && !empty($_POST['jaar'])){
// Create a new query object.
$query2 = $db->getQuery(true);

$query2->select('*');
$query2->from($db->quoteName($TABLE_NAME));
$query2->where($db->quoteName('jaar') .'='.$_POST['jaar']);
$query2->order('naam ASC');

// Reset the query using our newly populated query object.
$db->setQuery($query2);

$data2 = $db->loadAssocList();

$handle = fopen("inschrijvingen_".$_POST['jaar'].".csv", "w");

fwrite($handle, "naam,achternaam,geboortedatum,geslacht,telefoonnummer,email,adres,postcode,opleiding\n");

for ($i = 0; $i < count($data2); $i++){
    fwrite($handle, $data2[$i]['naam'].",".$data2[$i]['achternaam'].",".$data2[$i]['geboortedatum'].",".$data2[$i]['geslacht'].",".$data2[$i]['telefoonnummer'].",".$data2[$i]['email'].",".$data2[$i]['adres'].",".$data2[$i]['postcode'].",".$data2[$i]['opleiding']."\n");
}

fclose($handle);

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename("inschrijvingen_".$_POST['jaar'].".csv"));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("inschrijvingen_".$_POST['jaar'].".csv"));
readfile("inschrijvingen_".$_POST['jaar'].".csv");
exit;
}

Note: this is a joomla module

Milan
  • 133
  • 1
  • 8
  • check your csv file permission in the server – M0ns1f Aug 27 '17 at 11:06
  • https://stackoverflow.com/questions/125113/php-code-to-convert-a-mysql-query-to-csv –  Aug 27 '17 at 11:07
  • It all depends on where you have put this piece of code. The file you create is probably fine, check that, but this piece of PHP code is probably embedded into something that adds the HTML at the beginning. Moreover, you don't need to create a file, and then read it, just echo the data after the headers. – KIKO Software Aug 27 '17 at 11:07
  • You can take examples from here: https://stackoverflow.com/questions/125113/php-code-to-convert-a-mysql-query-to-csv –  Aug 27 '17 at 11:09
  • @KIKOSoftware you are right! Apparently Joomla adds some html to the file. – Milan Aug 27 '17 at 11:17
  • Have you thought about creating a .csv doc? The default type in Joomla is going to be html. – Elin Aug 29 '17 at 19:01

0 Answers0