unable to download csv string using header() in PHP [duplicate] - php

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.

Related

PHP Force Download [duplicate]

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.

How to convert Japanese character while downloading CSV using PHP [duplicate]

This question already has answers here:
Is it possible to force Excel recognize UTF-8 CSV files automatically?
(30 answers)
Microsoft Excel mangles Diacritics in .csv files?
(22 answers)
Closed 4 years ago.
There might be similar question, but I am sorry to say that I couldn't find that. So let me ask about my problem.
I have a PHP function to download CSV file from browser as below:
function outputCSV($data, $file_name = 'file.csv') {
header('Content-Encoding: UTF-8');
# output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=$file_name");
header('Content-Transfer-Encoding: binary');
# Disable caching - HTTP 1.1
header("Cache-Control: no-cache, no-store, must-revalidate");
# Disable caching - HTTP 1.0
header("Pragma: no-cache");
# Disable caching - Proxies
header("Expires: 0");
# Start the ouput
$output = fopen("php://output", "w");
fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM !!!!!
# Then loop through the rows
foreach ($data as $row) {
# Add the rows to the body
fputcsv($output, $row); // here you can change delimiter/enclosure
}
# Close the stream off
fclose($output);
}
After downloading the file, while open using Windows 10 Excel app the Japanese characters are wired. But can be viewed properly using Text Editor like NotePad++.
Is there any help on this?
Thanks.

echo blocking header function from being called [duplicate]

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.

headers already sent , export csv , can't download the file

im writing a basic script to download csv file based on database information,
in my dashboard/index.php i use GET and switch to include pages
so when i click on the link dashboard.php?link=export.php
i have a table with the all the data , there i have a link that i can download my csv file , my problem is that when i click to export.csv , i have an text output and not download file so i put those code :
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$filename}.csv");
header("Pragma: no-cache");
header("Expires: 0");
but always i see the content in text format and with an error
Warning: Cannot modify header information - headers already sent by (output started at /home/*/public_html/dev/dashboard/index.php:78) in /home/*/public_html/dev/dashboard/component/export.php on line 39
so i ask how can i resolve this issue , can i remove the header for the index in the export.php and set a new one also there to download the file or what extacly
maybe i need to change just in the export.php the Content-Type to be text/csv
but is alrady sent text/html .
please help to resolve this
thank you
As you can see, there is something already sent to output (printed) in your index.php file which is including your export.php file.
Make sure you are not printing anything before the headers. In some cases might be a space between the opening <?php tags or something little like that. btw mind that switch inclusion cases you have.
Other way is to try to use header_remove(); before the statements in export.php
Do not add anything before header in my case i was getting record from data base.
If you have function to download csv the add following header at top in the function like:
function exportCsv($date) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
.
.
.
.
}

forcing a file to download [duplicate]

This question already has answers here:
php - How to force download of a file?
(7 answers)
Closed 7 years ago.
I have a php page with information, and links to files, such as pdf files. The file types can be anything, as they can be uploaded by a user.
I would like to know how to force a download for any type of file, without forcing a download of links to other pages linked from the site. I know it's possible to do this with headers, but I don't want to break the rest of my site.
All the links to other pages are done via Javascript, and the actual link is to #, so maybe this would be OK?
Should I just set
header('Content-Disposition: attachment;)
for the entire page?
You need to send these two header fields for the particular resources:
Content-Type: application/octet-stream
Content-Disposition: attachment
The Content-Disposition can additionally have a filename parameter.
You can do this either by using a PHP script that sends the files:
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
readfile($fileToSend);
exit;
And the filenames are passed to that script via URL. Or you use some web server features such as mod_rewrite to force the type:
RewriteEngine on
RewriteRule ^download/ - [L,T=application/octet-stream]
Slightly different style and ready to go :)
$file = 'folder/' . $name;
if (! file) {
die('file not found'); //Or do something
} else {
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
}

Categories