0

My PHP app needs to provide my users with a single button that, when clicked:

  1. Executes a function that generates a .csv file and stores it on the server.
  2. Downloads that file to the user's client.
  3. Redisplays the same page that contains the button.

The best I have done so far requires two buttons. FYI, they look like this:

enter image description here

The "Generate Export File" button issues a POST that executes the file generator function. The HTML for this is:

<form enctype="multipart/form-data" action="season.php?#19" method="POST" name="export_meals_form">
  <input type="hidden" name="export_meals" value="docs/meals.csv">
  <p><input type="submit" value="Generate Export File" />
</form>

The "Download Export File" button is actually a link. The HTML for it is:

<p><a href="docs/meals.csv" download><button type="button">Download Export File</button></a></p>

If the user pushes these two buttons in the right order, everything works fine. But there's no reason why the user should have to do two clicks (and possibly get it wrong); the two actions are always supposed to happen together and in that order.

I think the problem is that I don't know how to initiate a download from PHP code. The only way I've found to do a download is for the user to click on a link with the "download" modifier, as above.

Several others have asked this question, and the usual answer sees to be to use the PHP readfile() function, embedded in code like this (from How to download file from database/folder using php):

    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($name));
    ob_clean();
    flush();
    readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
    exit;

When I invoke this kind of code from a PHP function, I get an error saying that the headers can't be loaded because the has already been sent. If I put the code in the , it simply displays the file contents in my browser and doesn't display the page.

I think there's something basic here that I don't understand.

1
  • try using an ajax call
    – Joshua
    Oct 28, 2019 at 4:06

2 Answers 2

0

The script you have posted, which is a derivative of the one in the manual (I have found the manual version to be a very reliable download example), should fall above any of your page html (or other browser output), so an example would be:

<?php
# I would still put session at the top
session_start();

# To create the file, use 
# Make this anywhere above any possible browser output
if(!empty($_POST['action']) && $_POST['action'] == 'export_meals') {
    # I would make the file noted on the php side, not sent by the form
    $file = "docs/meals.csv";
    # This would be the data to save to file
    $data = getDataFromSomePlace();
    # This will save the file to disk–not sure where you get the data...
    file_put_contents($file, $data);
    # Check if the file is really there and can be read
    if(!is_file($file) || !is_readable($file))
        die('File does not exists. Check path again.');
    # Do the default from-the-manual download script
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
# Now you can start all your other scripts and html
?><!doctype html>
<html>
...etc
<body>

<form action="season.php" method="POST" id="export_meals_form">
    <!-- I would just make this an "action" name, not the actual file path -->
    <input type="hidden" name="action" value="export_meals" />
    <input type="submit" value="Generate Export File" />
</form>

</body>
</html>

NOTE: I have modified your form a bit as well as the download script, but if you do it like this, it should work. In fact, I would create a new blank page, with no styles or other fluff and see if you can get it to work with just these basics. This script is tested and does work, so if it fails, you have implemented it incorrectly or your server is misconfigured in some way.

0

Thanks, Rasclatt - your solution was the breakthrough. The hard part was getting the download code in the right place in the PHP execution sequence.

In case my final code, which generalized the generator part to support download requests other than the "meals export" file that was the immediate need, may be of use to others, here it is:

<?php
if($_POST['file_to_download']) {
    // $filepath = "docs/meals.csv";
    $filepath = $_POST['file_to_download'];
    $parameters = $_POST['download_parameters'];
    $season_id = sqlSelect("id", SEASONS_TABLE, "current_season=1","")[0]['id'];

    // Call the generator function (if any)
    switch ($filepath) {
        case MEALS_EXPORT_FILE:
            exportMealsCSV($season_id, $filepath, $parameters);
            break;
    }

    // Put out the file
    // Code from the PHP manual: https://www.php.net/manual/en/function.readfile.php
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filepath)); 
    readfile($filepath);
    exit;
}
>

The PHP that produces the form that makes this particular download request looks like this:

function renderExportMealsForm($season, $action) {
    if (!$season) return;
    $form = '';
    $form .= '<form enctype="multipart/form-data" action="' . makeURI("season.php", PREVIOUS_CRUMBS_IDS, "", EXPORT_MEALS_ID) . '" method="POST" name="export_meals_form">';
        $form .= '<input type="hidden" name="file_to_download" value="' . MEALS_EXPORT_FILE . '">'; 
        $form .= '<input type="hidden" name="download_parameters" value="' . $action . '">'; 
    $form .= '<p><input type="submit" value="Download Export File" />';
    $form .= '</form>';
    if (0) deb("form = " , $form);
    return $form; 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.