How do I provide a download for existing Excel with PHP? - php

I have a generated xls file on my server that I would like to push to the client for download but can't seem to get it working. Here is what I have so far:
$xlsFile = 'test.xls';
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$xlsFile");
header("Content-Transfer-Encoding: binary ");
exit();
My excel file is correct and can be opened if I open it from the server but how can I push this file to the client for download?

You seem to be overdoing it with your "Content-type" headers. Oh, and you need to actually send the file before exit()ing. All you need is
header("Content-Type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="' . $xlsFile . '"');
readfile($xlsFile);
exit();

See this older post on the correct MIME type to send with your upload:
Setting mime type for excel document

Sample function.
function file_download($filename, $mimetype='application/octet-stream') {
if (file_exists($filename)) {
// send headers
header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK');
// type
header('Content-Type: ' . $mimetype);
// date of modified
header('Last-Modified: ' . gmdate('r', filemtime($filename)));
header('ETag: ' . sprintf('%x-%x-%x', fileinode($filename), filesize($filename), filemtime($filename)));
// file size
header('Content-Length: ' . (filesize($filename)));
header('Connection: close');
header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
// send file
echo file_get_contents($filename);
} else {
header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
header('Status: 404 Not Found');
}
exit;
}

You just need to add one more line
$xlsFile = 'test.xls';
header("Content-Type: application/vnd.ms-excelapplication/vnd.ms-excel");
header("Content-Disposition: attachment;filename='$xlsFile'");
header("Content-Transfer-Encoding: binary ");
echo file_get_contents($xlsFile);
exit();

Related

PHP : Force PDF file to download

i am trying to download a .pdf file on button submit, following is my code
if(mail('myemail#gmail.com', 'Brochure Downloaded ', $string)){
$text= 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url); // do the double-download-dance (dirty but worky)
}
Now whats happening is that email is sent but files is not downloaded, instead page gets reloading and long characters are printed on the screen ,
Need your help with this please
this is what i get
I have changed headers a little bit. I think the proper content type is application/pdf andsome of headers are not necessery.
if(mail('myemail#gmail.com', 'Brochure Downloaded ', $string)){
$text= 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='" . basename($file_url) . "'");
readfile($file_url); // do the double-download-dance (dirty but worky)
}
You may also add the content length:
header('Content-Length: ' . filesize($file_url));
check this code, first you need to add content type if you download any type file as like if you want to download image then
header('Content-Type: image/png'); if pdf then
header("Content-Type: application/pdf"); etc
<?php
if (mail('myemail#gmail.com', 'Brochure Downloaded ', $string)) {
$text = 'Your message recieved, We will contact you shrtly ';
$file_url = 'http://www.website.com/brochure.pdf';
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file_url");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
?>
you may use
header('Content-Length: ' . filesize($file_url));
you should use Content-Length if you want someone download a file with another header

Download file php in the server

in the localhost i get everything perfect but when i upload it to the server i get this error
Warning: Cannot modify header information - headers already sent by(
hier is my code
<?php
function download($file){
$dir = './download/';
$path = $dir.$file;
if(!file_exists($path)){
die('Error');
}else{
header('Content-Description : File Transfer');
header('Content-Disposition : attachment; filename='.basename($path));
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
ob_start();
flush();
readfile($path);
exit;
}
}
if (isset($_GET['download'])) {
if (!empty($_GET['download'])) {
$file = $_GET['download'];
download($file);
}
}
?>
<a class="download-template" href="example.php?download=Modern.rar">Download</a>
Remove the whitespace before the <?php
Like so
<?php
function download($file){
$dir = './download/';
$path = $dir.$file;
if(!file_exists($path)){
die('Error');
}else{
header('Content-Description : File Transfer');
header('Content-Disposition : attachment; filename='.basename($path));
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
ob_start();
flush();
readfile($path);
exit;
}
}
if (isset($_GET['download'])) {
if (!empty($_GET['download'])) {
$file = $_GET['download'];
download($file);
}
}
?>
<a class="download-template" href="example.php?download=Modern.rar">Download</a>
The error is telling you that you're outputting content before it should do.
If you output content then the page headers have already been sent, so your call to header() will fail because the headers have already gone. And headers are always sent first.
By removing the whitespace there is no content to send, so the headers are not sent, so the call to header will then work and not error.
Change the file encoding to "without BOM" (e.g. using notepad++) or remove the BOM before
Use the following code for download any type of file extensions(including .php,.html):
<?php
$filename = $test_data['test_name'];
$contenttype = "application/octet-stream";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile(ADMIN_ROOT.'modules/tests/test_pdfs/'.$filename);
exit();
?>
Or you can check in this link working example:
http://websamplenow.com/29/file_download

Why I'm unable to download a pdf file which is already present onto server?

Following is the code:
define(ADMIN_ROOT,'/var/www/abc/pqr/web/control/');
$filename = $test_data['test_name'];
$flname = ADMIN_ROOT.'modules/tests/test_pdfs/'.$filename;
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"" .$flname. ".pdf\"");
The pdf file is already present over there at the directory
/var/www/abc/pqr/web/control/modules/tests/test_pdfs/
Also it has all the permissions assigned.But when I try to download a file, it's downloading some different file with same name but the file is not in a format which could be opened. In short the desired file is not getting downloaded. Can anyone please help me in correcting my issue?
You must flush the file contents to the browser, headers won't do that.
So: readfile( $flname ) http://php.net/manual/pt_BR/function.readfile.php
Please try this
<?php
$filename = $test_data['test_name'];
$file = dirname(__FILE__) . "/modules/tests/test_pdfs/" . $filename;
//$file = "/var/www/htdocs/audio/" . $filename;
if (file_exists($file)) {
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=" . str_replace(" ", "_", basename($file)) . ";");
header ("Content-Length: " . filesize($file));
readfile($file);
die();
}
else {
//ERROR MESSAGE HERE..........
}
?>
Please change this line
header("Content-Type: application/pdf");
to
header ("Content-type: octet/stream");
You can also use the following code for download any type of file extensions:
<?php
$filename = $test_data['test_name'];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile(ADMIN_ROOT.'modules/tests/test_pdfs/'.$filename);
exit();
?>

try to download file and getting invalid file in response in core php

I download a file but it gives invalid file in return.
Here's my download_content.php
<?php
$filename = $_GET["filename"];
$buffer = file_get_contents($filename);
/* Force download dialog... */
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
/* Don't allow caching... */
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
/* Set data type, size and filename */
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($buffer));
header("Content-Disposition: attachment; filename=$filename");
/* Send our file... */
echo $buffer;
?>
download file link:
Download
$r['file'] contains the file name to be downloaded.
The complete path of the folder which contain the file is:
localhost/ja/gallery/downloads/poster/large/'.$r['file'].'
ja is the root folder in htdocs.
I don't know what the actual problem is, can anyone help me out please?
<?php
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
// print your data here. note the following:
// - cells/columns are separated by tabs ("\t")
// - rows are separated by newlines ("\n")
// for example:
echo 'First Name' . "\t" . 'Last Name' . "\t" . 'Phone' . "\n";
echo 'John' . "\t" . 'Doe' . "\t" . '555-5555' . "\n";
?>
As said in the other question, this way looks better:
$filename = $_GET["filename"];
// Validate the filename (You so don't want people to be able to download
// EVERYTHING from your site...)
// For example let's say that you hold all your files in a "download" directory
// in your website root, with an .htaccess to deny direct download of files.
// Then:
$filename = './download' . ($basename = basename($filename));
if (!file_exists($filename))
{
header('HTTP/1.0 404 Not Found');
die();
}
// A check of filemtime and IMS/304 management would be good here
// Google 'If-Modified-Since', 'If-None-Match', 'ETag' with 'PHP'
// Be sure to disable buffer management if needed
while (ob_get_level()) {
ob_end_clean();
}
Header('Content-Type: application/download');
Header("Content-Disposition: attachment; filename=\"{$basename}\"");
header('Content-Transfer-Encoding: binary'); // Not really needed
Header('Content-Length: ' . filesize($filename));
Header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
readfile($filename);
That said, what does "invalid file" mean? Bad length? Zero length? Bad file name? Wrong MIME type? Wrong file contents? The meaning may be clear to you with everything under your eyes, but from our end it's far from obvious.
UPDATE: apparently the file is not found, which means that the filename= parameter to the PHP script is wrong (refers a file that's not there). Modified the code above to allow a directory to contain all files, and downloading from there.
Your $filename variable contains whole path as below
header("Content-Disposition: attachment; filename=$filename");
Do like this
$newfilename = explode("/",$filename);
$newfilename = $newfilename[count($newfilename)-1];
$fsize = filesize($filename);
Then pass new variable into header
header("Content-Disposition: attachment; filename=".$newfilename);
header("Content-length: $fsize");
//newline added as below
ob_clean();
flush();
readfile($filename);

How to download PDF file from blob oracle using PHP?

I want to download blob file from oracle, that is PDF file, this is my code to get and download file:
<?php
$conn = ocilogon('user', 'pass', '//localhost/XE');
$sql = "SELECT PDFFILE FROM TFILE";
$stid = ociparse($conn,$sql);
ociexecute($stid);
$rowResult = ocifetch($stid);
settype($arrayResult,"array");
if($rowResult != null){
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . OCIResult($stid,'PDFFILE') . '"');
header("Content-Length: " . filesize(OCIResult($stid,'PDFFILE')->load()));
header('Content-Disposition: attachment; header("Content-Transfer-Encoding: binary\n");
}
?>
but when i run this code,i not get pdf file..
something wrong with my code??
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . OCIResult($stid,'PDFFILE') . '"');
header("Content-Length: " . filesize(OCIResult($stid,'PDFFILE')->load()));
header('Content-Disposition: attachment; header("Content-Transfer-Encoding: binary\n");
You're sending the Content-Disposition header twice. You probably don't even need the second one, the client should know all it needs to know about the stream from the Content-Type header. Omit the second Content-Disposition so you're not over-writing the header that has the filename.

Categories