1

In my main php file, I take an array and pass it to the client, I am using angular. This is what I am echoing...

header('Content-Type: application/json');
echo json_encode($response); //array passed to client

Now in my angular controller I am taking this data via GET request...

$http.get("../server.php").success(function(data) {
    $scope.names = data;
});

I have a download button in my index.php, when clicked, the controller takes this data and make a POST request to my submit.php file, sending the array to this file...

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

//array converted to a string called $template    

$contentFile = fopen("file.txt", "w");
fwrite($contentFile, $template);
fclose($contentFile);

The array is converted to a string then written to the file. Up to here, everything works. But the last chunk of code is never called...

header('Pragma: anytextexeptno-cache', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"file.txt\"");

I am attempting to force a download, but the header functions are ignored. I think this is due to the initial echo statement in the first excerpt of code above.

How can I fix this? How can I prevent the echo statement from cancelling out the header function? Do I need to redirect the page or something?

buydadip
  • 8,890
  • 22
  • 79
  • 154

1 Answers1

1

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

From PHP doc

The script must not produce any output for a call to header() to succeed and that header line actually be sent to the client agent.

You cannot "prevent echo from cancelling out header". Headers must precede the body of a response and echoing is part of the body. In your case, echo json_encode($response); (and any other output) should be produced after the last header() statement.

marekful
  • 14,986
  • 6
  • 37
  • 59
  • But if I put it before the echo statement, the force download will never be called because I need to echo the array to angular, and then pass it to the script that creates a file and allows the user to download the file. I think that if I put it before the echo statement there would be nothing to download, only an empty file – buydadip Sep 30 '16 at 15:39