I have a file, index2.php that has been written to by a form.
The whole content of this file, I have stored within a variable $final_code using an output buffer.
I now wish to add a "Download" button to the end of the page, that brings up a Save As dialog, allowing the user to save this file's source code (i.e. the variable) as a .txt - But I'm stumped.
index2.php:
<?php
// Start buffering the output
ob_start();
?>
<!-- INDEX2.PHP HTML ELEMENTS HERE -->
<?php
// Store the contents of the buffer
$final_code = ob_get_contents();
// Print the contents of the buffer
ob_end_flush();
?>
<form action="savefile.php" method="post">
Happy? Save this to file: <input type="submit" name="savefile" value="Save" />
</form>
I'm not sure if this needs to be worked in to this file or savefile.php, so the latter is currently blank.
i think you cannot force a save as file dialog in browser.
for forceing the download of a txt file i do the following:
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=\"example.txt\"");
echo $output;
hope that helps.
You need to use headers to force download:
$file = 'somefile.zip';
if(!file)
{
// File doesn't exist, output error
die('file not found');
}
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);
}
Example taken from:
http://www.ryboe.com/tutorials/php-headers-force-download
See link for further explanation.
Are you looking for PHP Download Script(from browser) ?
Related
I have read some answers here but i cannot seem to make my php script to work.
I generate a text or csv file (it depends what the user has chosen) from a form that it is submitted back to the same page.
The script works fine on Chrome, IE, Mozilla on my desktop but when i try on the stock browser on Android i get an attachment.html file that has the source of my script.
If i try with NEXT browser, i get a file with the proper filename but again inside is the source of my script.
I have read the following link but i cannot make it work
http://www.digiblog.de/2011/04/android-and-the-download-file-headers/
My http headers are the following
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($FileName) . "\"");
header("Content-Length: " . filesize($FileName));
header("Content-Transfer-Encoding: binary");
header("Expires: 0");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
header("Pragma: no-cache");
header("Connection: close");
print $Content;
exit();
-----Update 1----
I wrote the following code to test things out
<?php
$get = $_GET['get'];
if ($get == 1) {
$content = 'This is a line of text!';
$filename = 'superfile';
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($filename) . ".TXT\"");
header("Content-Transfer-Encoding: binary");
header("Expires: 0");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
header("Pragma: no-cache");
header("Connection: close");
echo $content;
exit;
}
echo '<html>
<head>
<title>Test</title>
</head>
<body>
<form method="get" action="index.php"
<label>Get</label>
<input type="text" name="get"/>
<input type="submit" name="ok" value="Send"/>
</form>
</body>
</html>';
?>
When i send the form with get method everything works, when i use post i get the html source that you see, same as the problem that i have with my original script.
-----Update 2-----
Okkkkk, now some more info, i think it is related to an Android bug, please check the following link
http://roscopeco.com/2013/04/android-and-the-form-post-download-problem/
Waiting for suggestions to work around this issue, i need method to me post because i pass too many varialbes and i don't want to have on big ugly url on the address bar.
Well, i didn't want to experiment too much so i get the user-agent and i change my post form to a get. Not a great fix but the job is done.
So I have been trying to get upload/download system to work but kept running into problems, specifically, the downloaded file being corrupt (.xls).
This is what I have currently:
<form action="{{block type=" core/template" name="my-template"
template="php/download_file.php" }}" method="post">
<label for="date">Date:</label>
<input type="date" name="date" id="date"><br>
<input type="submit" name="submit" value="Download">
</form>
download file
So, these both link to the same file and downloads fine.
If I click on the download file link, file opens perfectly fine.
If I go through the form download button, then it'll download but opening gives me a warning/error: "the file format and extension of 'file' don't match" and just hangs forcing me to force close the file.
download_file.php:
<?php
if($_POST['submit']) {
$file = 'excel_file.xls';
// Magento file path
$path = Mage::getBaseUrl('media') . 'folder' . DS . $file;
header("Content-Type: application/vnd.ms-excel");
//header("Content-Type: application/octet-stream");
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename = 'filename'");
echo $path;
exit;
}
?>
This is all in a Magento Static Block, in case that has anything to do with it.
Any help is appreciated.
Thanks.
Have you tried this:
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls"); //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
Greetings.
Try changing:
header("Content-Disposition: attachment; filename = 'filename'");
to:
header("Content-Disposition: attachment; filename=filename.xls");
Or if you use a variable:
header("Content-Disposition: attachment; filename=$filename.xls");
Basically, start and end with a quote and don't use any quotes or apostrophes in between.
I'm trying to download a CSV file through the browser. The script is partially working, because so far I managed to display the CSV on screen, but the download is not starting.
Here is what i tried so far:
if(isset($currency)) {
header("Content-Type: application/csv");
header("Content-Disposition: attachment;Filename=Pricelogs.csv");
ob_clean();
$filename = "/tmp/".uniqid().".csv";
exportCSVFile($filename, $currency, $country, $provider);
readfile($filename);
//unlink("'".$filename."'");
} else {
echo "ERR_USERNAME_PASSWORD";
exit();
}
I had already read all questions of this type from FAQ & also tried but it gets open on browser only,instead of downloading.
I had also used header with single quotes.
I also tried header("Content-Type: text/csv");
Also:
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");
PUT your CSV file URL, it will display in browser in place of force browser to download. You can open it in iframe in your site.
http://docs.google.com/viewer?embedded=true&url=www.yoursite.com/filename.csv
I usually just do:
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=my_csv_filename.csv");
// print CSV lines here
exit();
I can tell you this combination is working for me:
$bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
header("Content-type: application/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
print $bom . $data;
exit;
If I were you, I would first test this plainly (outside of all your buffering), first see that you manage to make this work, and only then test it in your specific set up.
You might try this.
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: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename.csv\";" );
print $content;
For large files you need to get your output buffer started
add : ob_start(); at the start
ob_clean(); at the end of you file
i have this code for image download in php... works fine, image downloads but the problem is that it does not open in the place where it gets downloaded, and gives the error " Can't read file header...Unknown file format! "
<?php
$path = $row['img_url'].".jpg";
echo $path;
$filename = $path;
$ctype="application/.jpg";
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
?>
Change the content type
$ctype="application/.jpg"; //It's a invalid content type
to
$ctype="image/jpeg";
you should not be echoing anything before the header and try using header('Content-Type: image/jpeg');
Try using image/jpeg MIME type instead of application/.jpg
Your content type is wrong. Try to use $ctype="image/jpeg";
below is some part of code in my download gateway
if (!isset($_GET['f']) || empty($_GET['f'])) {die("<h1>URL Malfunction</h1><br/><p><i>Please Try Later</i>");}
if (strpos($_GET['f'], "\0") !== FALSE){ die("<h1>URL Malfunction</h1><br/><p><i>Please Try Later</i>");}
#Check URL, find resource Path
$fileName = basename($_GET['f']);
$file_path=(string)makeDownloadFilePath($fileName,"dir");
if(!is_file($file_path)){die("<h1>404 Not found</h1><br/><p><i>The resource you requested is not available</i>");}
$fileSize = filesize($file_path);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public"); #Build Response#
header("Content-Description: File Transfer");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fileSize);
$file = #fopen($file_path,"rb");
if ($file) {
while(!feof($file)) { #File Transfer#
print(fread($file, 1024*8));
flush();
if (connection_status()!=0) {
#fclose($file);
die();
}
}
#fclose($file);
//The File is Downloaded . Closing Connections
I am using GET method to receive the filename. The filename and its path will e genrated from gateway. Now the problem is When i click on download in a page, instead of showing a Download dialog, the browser just renders the file content as text on screen. For eg, i am downloading foo.mp3. the binary contents are displayed as weird text on screen.
Its echoing a warning like: We cannot change the Headers. headers already sent to ...
Can any one tell , where i had made the mistake?
Thanks
We cannot change the Headers. headers already sent to..
This error comes when you print any thing before php your header command.
The most common cause of this error by a long, long way is that you have some leading white-space before the opening <?php tag in your file (or one of it's includes).
The < should be the first character in the file, anything before it is written to the output buffer directly and will probably result in the headers being sent. When forcing file download in this manner, it will also result in corrupted files.
Use readfile instead of fopen as follow and use ob_clean() , ob_flush() :
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$Name.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: '.filesize($musicPath));
ob_clean();
flush();
readfile($musicPath);
ob_flush();
Are you using the output buffer?
try adding ob_start(); before you send out the header information, this may solve your issue.
You can find out more information about it here
Thanks all for the help. The problem was i was using a
error_reporting(E_ALL);
ini_set('display_errors', true);
flush();
for debugging in one of my includes.
I just removed it.Now it works.