This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
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?
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.
Related
This question already has answers here:
Handle file download from ajax post
(21 answers)
Closed last year.
I am new to php and ajax. Im trying to force download a file from a list of documents. The functions below gets triggered using an ajax call after a button click.
function downloadDocument($filename) {
$file_path = ".........../DocUploader/Uploads/" . $filename;
if (file_exists($file_path)) {
header("Content-Description: File Transfer");
header("Content-Type: application/json");
header("Content-Disposition: attachment; filename=\'" . $filename);
readfile($file_path);
} else{
echo "Document does not exist";
}};
Instead of downloading the file, I assume I am getting the file content as a response. I would really appreciate any advise on what I should do.
First remove any echo's or output to the browser before sending any header, ie. remove the echo "File exists";
The file name should be encapsulated in quotations, ie. Content-Disposition: attachment; filename="filename.ext"
<?php
header("Content-Description: File Transfer");
header("Content-Type: application/json");
header('Content-Disposition: attachment; filename="'. $filename .'"');
readfile($file_path);
Keep in mind to set correct Content-type based on the real kind of the downloaded document, see topic What are all the possible values for HTTP "Content-Type" header?
You can dynamically detect the MIME type using PHP function mime_content_type()
And reference for PHP header.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I am working on hosting a mirror of a site using a standard LAMP stack. When trying to return a generated image the Content-type header is not getting set correctly to image/png and is instead returning as Content-Type:text/html; charset=UTF-8. This is causing the browser to just show a steam of garbage rather than an image. I have the function that is attempting to set the headers and have added some of my own debugging to the code, but don't know where to go from here.
// Generate image header
function Headers() {
error_log("in Headers function",0);
// In case we are running from the command line with the client version of
// PHP we can't send any headers.
$sapi = php_sapi_name();
error_log("sapi = $sapi",0);
if( $sapi == 'cli' ) return;
// These parameters are set by headers_sent() but they might cause
// an undefined variable error unless they are initilized
$file='';
$lineno='';
if( headers_sent($file,$lineno) ) {
error_log("headers already sent",0);
$file=basename($file);
$t = new ErrMsgText();
$msg = $t->Get(10,$file,$lineno);
die($msg);
}
if ($this->expired) {
error_log("expired",0);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
}
header("Content-type: image/$this->img_format");
header("Custom-header: gnm image/$this->img_format");
error_log("end of Headers function, img_format = $this->img_format",0);
}
With the above code I get the error log showing that I have entered the function, the sapi is apache2handler, expired is true, the image format is png, and that I am at the end of the function. I also get all headers in the expired block set correctly and the added "Custom-header" gets set as expected. The only header that isn't set as expected is the Content-type.
This function is being called from a php file that is generating and then streaming an image. Any and all help tracking this down is appreciated.
Make sure your calls to header are the very first thing that would be echoed to the browser. If anything is echoed before header is called, the content type is automatically set to text/html.
Look like a problem I got once.
Make sure you dont add BOM to your file, it causes headers to fail because it won't be the first thing to be written in the file.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I read a whole bunch of articles in SO and the internet and tried all of them but I am still unable to create a CSV download functionality in PHP.
Following is my code:
$csvData = #$_POST['csv_data'];
if(trim($csvData))
{
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=data.csv");
header("Expires: 0");
header("Pragma: public");
echo $csvData;
exit;
}
Instead of showing the file save dialog, this keeps printing the CSV data into my browser :( What am I doing wrong here? Any help is much appreciated..
Additional Edit: I am posting this data into my script, which immediately takes this data and tries to download. My script is an include inside another file, will that be a problem? I enabled error_reporting and found that I am getting header already modified error...
In HTTP, headers are sent before any text output.
For that reason, PHP will close your response header if you output any text.
Make sure that you hold any text output before your header modification, for example using the OB-cache.
I need to create a PHP page which starts automatically the download a file (I don't want to expose the Download link). I've tried with several examples on the web but all examples will end up with opening the file in the browser with the uncorrect content type.
For example:
<?php
// We'll be outputting a ZIP
header("Content-type: application/zip");
// Use Content-Disposition to force a save dialog.
// The file will be called "downloaded.zip"
header("Content-Disposition: attachment; filename=downloaded.zip");
readfile('downloaded.zip');
?>
When I execute this page, the output on the browser is:
After trying all possible variants of this example my idea is that the problem is with my hosting environment. Which variable should I check and maybe ask to be enabled to my provider ?
Thanks!
Try printing out the following variable using phpinfo(): SERVER["HTTP_ACCEPT_ENCODING"].
My suspect is that you don't have zip allowed- could be something different like "gzip" for example.
Here's the code I used back in the day: header ("Content-Type: application");
header ("Content-Disposition: attachment; filename=\"$file\"");
header ("Content-Length: " . filesize ('./FILES/' . $file));
header ("Cache-Control: no-cache");
header ("Pragma: no-cache");
readfile ('./FILES/' . $file);
Just modify the content-type header ofc.
I am trying to serve up a dynamically generated csv file. For some reason when I get the file, there are 18 empty rows preceding the data. I don't have any space between the headers I define and the csv data I'm sending. If I write the data to a file on the server, it does not get these empty rows. However, if I write the file and then try to serve it to the user, the empty lines come back. So I'm wondering if perhaps I've messed up the headers, or if perhaps there is another issue I'm not thinking of:
function generate_csv($source_type, $include_unpublished = FALSE) {
// retrieve data from DB
....
// start up headers
$csv_name = "$source_type-$data_set-csv_" . date('Y-m-d') . '.csv';
header('Content-Type: text/x-comma-separated-values');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browser
header('Content-Disposition: attachment; filename="' . $csv_name . '"');
// send csv data
print $csv_data;
} //end function
Disclaimer: I asked this question at https://drupal.stackexchange.com/questions/27649/extra-empty-rows-when-serving-csv-file, but it dosn't seem to be drupal-specific and there weren't many ideas coming up over there..
Maybe this lines "hang" in an output buffer, that were started some time before. This way you can set headers without the good old "headers already sent"-error, but this content will be send to the browser when flushing the buffer anyway.
Try
ob_clean();
print $csv_data;
http://php.net/ob-clean
It must be problem with files that you are including. Every whitespace more than one newline after php closing tag ?> is sent to the browser.
Best solution is to get rid of this closing tags in every php file.
Other option will be to remove only unnecessary new lines from them or to bufer output and disregard it before serving file.