0

I'm pretty new to this.

I use the following code to allow users to download specific files directly off the website. They first select a category/map, which is posted. Then they select a file from the map and input their name (Which is saved in a CSV) and the file download starts.

Anyway the code which downloads/saves after the POST is as such:

    if($_POST['fileselecto']!=''){
        $file_destination = $_POST['fileselecto'];
        if(file_exists($file_destination)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file_destination).'"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_destination));
            readfile($file_destination);
            exit;
        }
        $data = array(array("aanvragen", $_POST['name'], " ", " ", "", " ", $_POST['fileselecto']));
        $location = 'csvinfo/aanvragen.csv';
        $fh = fopen($location, 'a');

        foreach($data as $rec):
            fputcsv($fh, $rec);
        endforeach;
        fclose($fh);
        }else{
        echo 'Error';
    }

The problem however is that I get errors as such:

Warning: Cannot modify header information - headers already sent by (output started at 
/var/www/myhost/index.php:227) in /var/www/myhost/pages/aanvragen.php on line 45

As far as I can tell this is because the way I set up my page is an overlaying index page with a bunch of functions, then it loads in the information from .php files that echo functionality.

My question: Does this mean that I can never use readfile properly? My files are 'opened' on the page rather than forced to download. Is there a way to bypass this?

Edit: A workaround/sollution here is to put the above code in a download.php which is triggered when the form gets posted rather than executing the code in the page.

  • The error basically means that you've already emitted some output before this code. Are you sure this is all of the code? Maybe there's even just some whitespace before the opening ` – David Oct 17 '19 at 23:22
  • I've read through the first comment here gre_gor, i'm aware that there's already been output. But the output seems to be from the overarching 'Index.php' file that I'm loading my page into rather than the page itself. The sollution to this that I've found is to make my form link to an action download.php with the above code, which works like a charm. – Silvano W. Oct 17 '19 at 23:43
  • 1
    you need to paste ALL of your code for us to debug - most likely your architecture is incorrect and will need to be redone – Dan Oct 17 '19 at 23:55

0 Answers0