php – Download csv scripts work on my xampp localhost but don't work on my Siteground website-ThrowExceptions

Exception or error:

I have a small web application. It consists of three main parts – MySQL database that lives on a secure VPS server, front end for users to fill up forms, and another admin front end for admins to review and process them. Admins requested a download button; on the list view where forms are displayed as a table and on form view where individual forms are displayed.

It works as expected on my xampp localhost installation but when I put it up on my web host, it behaves differently. In this question, I’d like to resolve the issue with the list view download.

Locally, it outputs a csv file with the header and values as you’d expect. It doesn’t redirect or change the HTML.

Live, it doesn’t download the file at all, and instead displays comma-separated values on the screen.

Here’s the relevant code:

include_once 'dbConnect.php';
include_once 'config.php';
include_once 'header.php';

$select = implode(",", $display_fields);
$select_hidden = implode(",", $hidden_fields_for_download);

$sql = 'SELECT '. $select .','. $select_hidden .' FROM applicants ORDER BY id';
$res = $mysqli->query($sql);

# get a nice associative array
$applicants_data = $res->fetch_all(MYSQLI_ASSOC);
# $columns only used in list.js sorting
$columns = array();

    $columns = array_keys($applicants_data[0]);
else {
    echo "<h1 class='margin-xl text-centered'>No applications have been submitted.</h1>";

if (isset($_POST['download'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=kmf-forms.csv');
    foreach ($applicants_data as $index => $row) {
        if ($index == 0) {
            foreach ($row as $key => $value) {
                #if $key it's in the field_titles, show the user friendly title
                #Otherwise, show field name from the database
                if (in_array($key, array_keys($field_titles))){
                else {
        #index+1 because index 0 is now header
        $user_CSV[$index + 1] = array_values($row);
    $fp = fopen('php://output', 'wb');
    foreach ($user_CSV as $line) {
        fputcsv($fp, $line, ',');

If any other parts of the file are likely relevant, please let me know and I will include them.

My question: Why does it behave differently live? What should I change to duplicate functionality I built for the local installation?

P.S. I’m self-taught and not a PHP expert, so I’m sure there are various issues with my code regardless of the issue on hand, and I’m happy to hear criticism, but would truly appreciate the help with my problem specifically.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *