PHP Header & CSV WITH NO download option - php

I have written a script using header function that generates CSV file.Let me explain in detail.
Step 1) I am saving records in mysql.Step 2) I am creating CSV file from saved records from database Step 3) I want to attach that CSV in attachments so that i could send it to different recipents!! I have completed the two steps.But i dont want download functionality in CSV file generation process as i dont want this file available to anyone. My code looks like this:
$file_name = "Register_" . date('l');
$file_name.=".csv";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$file_name");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Where do I need to make changes?

just remove all calls to header() and the last print

You could do what you try to by using the ob_buffer functions and 'catching' the generated output. However the whole approach is a little strange:
the header functions have nothing to do with creating emails. They serve the purpose to specify how a browser should handle transferred data. 'Cause this is what you do: you send headers and data. Don't.
Instead: write the csv data into a buffer or file and create an email using one of the available email classes (google...). Then take that crafted email and send it. No header() function required for that.

You can use AddStringAttachment:
$file_name = "Register_" . date('l') . ".csv";
$excelContent = "$header\n$data";
$phpmailer->AddStringAttachment($excelContent, $file_name, 'base64', 'application/vnd.ms-excel');

Related

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');
.
.
.
.
}

My PHP generated CSV file is saving as a PHP file

I've learned how to create CSV files from MySQL data from another StackOverflow question. My problem is, for some reason when I call this code, it tries to save a file called index.php (which is the current page). Inside the index.php file my data from the table is there, separated by commas. I'm guessing I have a small typo somewhere, but after playing with the code I cannot find it. Thanks to anyone who can help.
$result=mysql_query("SELECT * from tbl_email");
if(mysql_num_rows($result)) {
header ("Content-type: application/csv Content-Disposition:\"inline; filename=messages.csv\"");
echo "REF #,Company,Name,Email,Message,Date\n";
while($row = mysql_fetch_row($result)) {
$companyname = mysql_query("SELECT company FROM tbl_users WHERE user_id ='$row[1]'");
$datname = mysql_fetch_array($companyname);
echo"$row[7],$datname[company],$row[2],$row[4],$row[5],$row[6]\n";
}
die();
}
You need multiple header() calls rather than one call which supplies multiple headers on a single line, and I believe the most appropriate mime type for a CSV is text/csv.
header("Content-type: text/csv");
header("Content-Disposition: inline; filename=messages.csv");
And more commonly, we would use Content-Disposition: attachment to force a download.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=messages.csv");
It should be:
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="messages.csv"');
Notice that the value for filename is not encased correctly with double quotes. Try to use single quotes in php, this will save you alot of trouble. ;)
Have a look at http://www.techcoil.com/blog/php-codes-to-tell-browsers-to-open-the-download-dialog-box-for-users-to-download-a-file/ to learn more about telling browser to download your file.

Save pdf to local server

I am creating a PDF file from raw binary data and it's working perfectly but because of the headers that I define in my PHP file it prompts the user either to "save" the file or "open with". Is there any way that I can save the file on local server somewhere here http://localhost/pdf?
Below are the headers I have defined in my page
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Transfer-Encoding: binary");
If you would like to save the file on the server rather than have the visitor download it, you won't need the headers. Headers are for telling the client what you are sending them, which is in this case nothing (although you are likely displaying a page linking to you newly created PDF or something).
So, instead just use a function such as file_put_contents to store the file locally, eventually letting your web server handle file transfer and HTTP headers.
// Let's say you have a function `generate_pdf()` which creates the PDF,
// and a variable $pdf_data where the file contents are stored upon creation
$pdf_data = generate_pdf();
// And a path where the file will be created
$path = '/path/to/your/www/root/public_html/newly_created_file.pdf';
// Then just save it like this
file_put_contents( $path, $pdf_data );
// Proceed in whatever way suitable, giving the user feedback if needed
// Eg. providing a download link to http://localhost/newly_created_file.pdf
You can use output control functions. Place ob_start() at beginning of your script. At the end use ob_get_contents() and save the content to a local file.
After that you can use ob_end_clean() or ob_end_flush() depending on whether you want to output PDF to browser as well, or you would redirect user to some other page. If you use ob_end_flush() make sure you set the headers before flushing the data.

PHP generated Excel file is different when downloaded

I have a PHP file that generates xls files using the module found at http://pear.php.net/package/Spreadsheet_Excel_Writer/
I can create the sample document just fine and when I open it, it looks fine.
My next step it to turn it into a downloadable link. To do that, I did this:
$mimeType = "application/vnd.ms-excel";
$file_name = "test.xls";
$file_path = "/tmp/".$file_name;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Type: application/' . $mimeType);
header('Content-Length: '.$size);
header("Content-Disposition: attachment;filename=$file_name ");
header("Content-Transfer-Encoding: binary ");
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = & fopen($file_path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
When I download the file however, it contains a lot of garbage data both in Excel and OpenOffice. The diff says that then binary file in the /tmp folder and the downloaded file are different from each other. I'm guessing that it has something to do with the headers or with fpassthru but I haven't had much luck with debugging the issue.
Any ideas on what the problem is?
The multiple Content-Type headers are uncessary. You're essentially saying that the file is a muffin and a pizza and a ford taurus all at the same time. All you need is the application/octet-stream version, unless you want to serve up the exact mime type.
As well, is there any reason you're trying to turn the file handle returned by fopen() into a reference?
Try something simpler:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment;filename=$file_name");
readfile("/tmp/test.xls");
exit();
?>
and see if that does any better.
Just make sure that you don't send ANYTHING out to the browser BEFORE the actual file content gets send.
It might just be some php 'error' or even 'notice' that Spreadsheet_Excel_Writer is producing and you don't even see. Or it might be a closing '?>' tag thats followed by s simple space or newline.
I had a similar error where the file that was generated inside the web folders were working. However the delivery using header('...') gave me corrupt files. This was due to a single space at the end of one php file after the closing '?>' tag.
I am using the same library and I just discovered that the files in the library itself are creating the whitespace.
Solution: In the following files remove the whitespace at the end of the file, or remove the ?> closing tag at the end.
Files to edit (all files in the Spreadsheet_Excel_Writer package):
Writer.php
Workbook.php
Worksheet.php
PPS.php
Parser.php
OLE.php
Parser.php
File.php
BIFFWriter.php
Validator.php
Root.php
Add the following code at the top of the page where the excel file is generated
ob_clean();
This would clear all the gibberish data.Also check for any echo statements.If echo statements are present, remove them. The data should always present in format specified by excel package.

Can you use AJAX to echo out a file for download?

I wanted to let a user download a file by simply clicking a button. Thing is, the file doesn't actually exist - its just some dynamic content.
So lets say:
$('a.download').click(function(){
$.post('get.php');
})
and in my PHP:
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=something.txt");
header("Content-Type: text");
header("Content-Transfer-Encoding: binary");
echo 'abcbdefg'
Is that valid? Is there some other way to do it?
Just create a link to the file, like this:
download my file
Whenever there's a request for a file of type PHP, your webserver will first process the file and output whatever text it contains to the client; you don't have to do anything special just because it's dynamic.
Using $.post() doesn't make sense for what you want to do; that POSTs data to the url you specify, it doesn't prompt the user to save a file.
Yeah, that's valid. I'm pretty that's the best way to do it.

Categories