Bolboa Bolboa - 2 months ago 9
AngularJS Question

echo blocking header function from being called

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?

Answer

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.

Comments