Unable to force download file with PHP - php

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.

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

PHP send stream to browser as zip archive

I am making a call(PHP server) to an API and I can confirm that I am getting a response, my code at the point where I know I am getting a response is:
$binaryF = $rsObject->makeCall('get', "/JobData/{$_GET["jID"]}", "?format=bin");
//header("Pragma: public"); // required
//header("Content-Type: application/zip");
//header("Content-Disposition: attachment; filename=ss.zip");
//header("Content-Length: " . filesize($binaryF.length));
//header("Content-Transfer-Encoding: binary");
file_put_contents('C:\ss.zip', $binaryF);
If I keep the code as is and click on the link that takes me to the page with this code on it, ss.zip is created and I open it and confirm that it has the correct content. The data is coming from an API call on the first line and is basically a zip package. If I remove the comments and comment out the file_put_contents line then the browser opens a file save dialog box but if I save it the archive is 0 bytes?
How do I send the content to a browser after retrieving it from the api call? I do not want to save it to disk first, I want to send it to the browser making the request directly.
Thank you
Jack
Ok. I changed it to:
header("Pragma: public"); // required
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=ss.zip");
header("Content-Length: " . strlen($binaryF));
header("Content-Transfer-Encoding: binary");
and now it opens the file save. I save it and it is 8 K but when I try t oopen it I get a message of: "Windows cannot open the folder" It complains that the zip is invalid? At least I am getting somewhere, thanks for the help so far!
Try (untested):
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename=ss.zip');
echo $binaryF;
$binaryF would need to be a string value for the filepath to the file you are trying to serve up in order for filesize() to work.
You can use strlen() to get the filesize for use in the ContentLength header.
You of course still need to actually output the file to the client browser.
I had some similar problems with PDF's, for me the Content-Length couldn't be calculated correctly with strlen() because it doesn't support multibyte-characters.
instead try this:
header("Content-Length: " . mb_strlen($binaryF));
See the documentation for more detailed information: http://www.php.net/manual/en/function.mb-strlen.php
Ok, #zerkms helped me by pointing out that I should use: strlen($binaryF) instead of filesize($binaryF.length) He helped me in a chat session by telling me to open the zip archive(with something simple like notepad) that I did get with file_put_contents('C:\ss.zip', $binaryF); This showed that what was produced was only partially correct, there was some HTML content that slipped into the response of the actual call. So all credit goes to #zerkms, thanks.
What worked? the following worked for me:
header("Pragma: public"); // required
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=ss.zip");
header("Content-Length: " . filesize($binaryF.length));
header("Content-Transfer-Encoding: binary");
echo $binaryF

Retrieving output from a url. How do I force the dowload of a PDF from a url using php

I need to retrieve our reports from the jasperserver report engine as a PDF, then I want the PDF to be forced as a download, instead of being displayed inthe browser. The problem with displaying in the browser is we don't want the report parameters to be displayed to the end users in the url.
If I enter this URL path into the browser I get a PDF document that shows in the same browser window with all the report data:
https://mysite.com:8443/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=sample_report&output=pdf;
What I would prefer to have happen is for a download dialog box to be used and for the users to download the PDF to their computer, instead of it showing in the browser.
I've tried the following php code, but can't get it to work. I get a return value of false, but nothing in the server logs that shows an error.
ob_start();
header("Location: $src"); /* Redirect browser */
$report_contents = ob_get_contents();
ob_end_clean();
var_dump($report_contents);
I'm not really sure how to go about this...anyone got any ideas?
Thanks for the help.
You could buffer the file to the PHP server then output with force download:
header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');
readfile('https://mysite.com:8443/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=sample_report&output=pdf;');
See the notes about using readfile over an HTTP stream wrapper
http://php.net/manual/en/function.readfile.php
how about
$source=$url
header("Expires: 0");
header("Cache-Control: private");
header("Pragma: cache");
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
readfile($source);
exit();

PHP File Download

I'm currently building a script that will allow a user to download a file via a URL without actually seeing the filename or where the file is stored. So far I have everything built out, but I need to know how I would go about calling the file to open and download. I currently have a working version (code below), but for some reason the PHP is corrupting the download. Everytime I try to open a file that downloads to my desktop I get a corrupt error message. When I open the same file on the server itself, the file works just fine.
URL Structure:
http://www.example.com/download/file/cjVQv0ng0zr2
Code that initiates the download
$fullpath = BASE_PATH . '../uploads/brochures/' . $vendors['0']['filename'];
header("Content-type: application/pdf");
header('Content-disposition: attachment; filename="' . $fullpath . '"');
Am I doing something wrong that would cause the file to become corrupt? Am I missing a header or two?
Thanks in advance,
Jake
You need to call the following line after sending the header.
readfile($fullpath);
and also adjust in the header like this:
header('Content-disposition: attachment; filename="' . basename($fullpath) . '"');
One thing i am not sure about is the $fullpath .. try to see if the $fullpath you have is correct and you can actually reach the file, this needs to be the full physical path of the file.
I think it would also be a good idea to add the following header as well:
header("Content-Transfer-Encoding: binary");
I had a similar issue a while back. Make sure you don't have any extra whitespace in your script file, either before the "<?php" tag or after the "?>" tag. In my case the last character of my script was "\n" instead of the expected ">".
I had faced the same problem sometime back, following worked for me; put a
while( #ob_end_clean() );
just before header functions:
header("Content-Type: ". $row['p_mime']);
header("Content-Length: ". $row['p_size']);
header("Content-Disposition: inline; filename=".$row["p_name"]);
Content-disposition: attachment/inline has to be set according to cases (1. prompt for download / 2. open in browser)
NOTE: Take care that you are not echoing and value before the header function, and being over cautious will not do any harm, silent out all the function before header function which you think would fail or spawn a warning message prefixing "#" symbol to those lines of php code.
all the best :)
Make sure you exit...
(i'm using a blob)
header("Content-Type: " . $response['content_type'] );
header("Cache-Control: maxage=1");
header("Pragma: public"); //fixes ie bug
echo trim($_data);
exit();

php force download xml

I am creating an xml file on the fly. When a user generates this file I want it to open up a download file dialog with the content that was generated. There is no actual file because it is just generated through php. Any ideas on how to do this?
This is what worked for me. In readfile('newfile.xml'); make sure to give the path of the file correctly. This php page is called from an html page with anchor tag which says - download:
<?php
header('Content-disposition: attachment; filename="newfile.xml"');
header('Content-type: "text/xml"; charset="utf8"');
readfile('newfile.xml');
?>
source: How do I force the browser to download a file to disk instead of playing or displaying it?
Send a content-disposition attachment header.
header('Content-disposition: attachment; filename=advertise.xml');
header ("Content-Type:text/xml");
//output the XML data
echo $xml;
// if you want to directly download then set expires time
header("Expires: 0");

Categories