i was trying to force download pdf files on my website. The file was downloaded successfully but an empty file is created in the same folder with a random name when download is clicked. i'm having multiple null files in the folder.
download.php :
<?php
$file = $_GET['file'];
header('Content-type: application/pdf');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="'.$file.'"');
?>
Assuming you store your pdf in database.
//you need to decode
$decoded = base64_decode($downloaded->pdf);
//name of pdf
$filename =date('Ymdhis').'.pdf';
$size=strlen($decoded);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.($filename).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header('Content-Length:'.$size);
echo($decoded);
exit;
Please note, if you send some headers before it will not working.
Make sure you create properly your pdf file.
$decoded = base64_decode($downloaded->pdf);
$filename =date('Ymdhis').'.pdf';
//if file doesn't exists
if(!file_exists($filename)){
//we create file in the location
$fp=fopen($_SERVER['DOCUMENT_ROOT'].'/tmp/'.$dir_name.''.$filename,'a+');
//We write in
fwrite($fp, $decoded);
}
Now, the CSV file is exported in reports folder. Instead i want the browser to ask where to export the file. so that i can export the file in desired location of client machine and avoid storing those files in server (i.e)reports folder.
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$selProducts= $this->db->query("SELECT * FROM tablename");
$data= $this->dbutil->csv_from_result($selProducts);
$randomidgenerated = "reports/".date('Y-m-d').".csv";
if(file_exists(FCPATH.$randomidgenerated)){
$randomidgenerated = "reports/".date('Y-m-d')."_".random_string('alnum', 3).".csv";
}
if ( ! write_file($randomidgenerated, $data))
{
echo 'Unable to write the file';
}
$data = file_get_contents($randomidgenerated);
force_download($randomidgenerated, $data, TRUE);
from what i can see you are just creating the contents of the file to be downloaded dynamically... What you have to do now is force the browser to download the file to the clients chosen part then probably delete the temporary file afterwards if you dont want to store it on the server... Add the code below just after you have created the file or sure of its existence... something like
$file = FCPATH.$randomidgenerated;
if(file_exists($file)){
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
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($file));
ob_clean();
flush();
readfile($file);
exit;
}
That should do it.
Hi I am trying to allow download a demo file which is related to a product. my code is like this
if(isset($_POST['submit'])){
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/download/";
$path = $root.$path;
$filename = $demo;
$file = $path.$filename;
header('Content-Type: application/force-download');
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
readfile($file);
}
I am able to get file name which is associated with the product by
$demo
After user submits his information, download will start automatically. Now this is downloading a non existing file or corrupted file with the proper file name. please help
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
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($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
As you can see Content type is application/octet-steam meaning file is byte by byte encoded. Also the cache headers are set. Then headers are forcefully sent by ob_clean();flush(); and then the file is read.
The file_exists is there to ensure that given file exists. You should also try not not thrust user input as they could easy write names for your php codes and download EACH file. And with ../ in names of the files, even your documents or system files and so on.
What I want to do is to allow only one download per user (one access to a href) For that I have a variable in the user's table, which I do change when the link has been clicked.
I use "download.php?file=file.xxx" for doing that.
download.php
$file= basename($_GET['file']);
$root = "documents/rece/";
$path= $root.$file;
echo $path;
if (is_file($path))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
}
else
echo "File error";
exit();
?>
I also update the DDBB and that works. After that I can show or hide the link. The problem is that the downloaded file is corrupted and can't be opened. I will use it with pdf or doc, maybe zip.
Could it be because of the path?
PDF files, as far as I know, start with something like this:
%PDF-1.4
Yours start with 4 blank lines plus documents/rece/Form.pdf%PDF-1.4. You're obviously printing it yourself somewhere before the code you've posted.
I'm trying to use PHPWord to generate word documents. And the document can be generated successfully. But there is a problem where my generated word document will be saved on the server. How can I make it available to download straight away?
Sample:
$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
$document->save('php://output'); //it auto save into my 'doc' directory.
How can i link to the header to download it as follows:
header("Content-Disposition: attachment; filename='php://output'"); //not sure how to link this filename to the php://output..
Kindly advise.
php://output is a write-only stream, that writes to your screen (like echo).
So, $document->save('php://output'); will not save the file anywhere on the server, it will just echo it out.
Seems, $document->save, doesn't support stream wrappers, so it literally made a file called "php://output". Try using another file name (I suggest a temp file, as you just want to echo it out).
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
In the header, the filename field is what PHP tells the browser the file is named, it doesn't have to be a name of a file on the server. It's just the name the browser will save it as.
header("Content-Disposition: attachment; filename='myFile.docx'");
So, putting it all together:
$PHPWord = new PHPWord();
//Searching for values to replace
$document = $PHPWord->loadTemplate('doc/Temp1.docx');
$document->setValue('Name', $Name);
$document->setValue('No', $No);
// // save as a random file in temp file
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
$document->save($temp_file);
// Your browser will name the file "myFile.docx"
// regardless of what it's named on the server
header("Content-Disposition: attachment; filename='myFile.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file); // remove temp file
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$filename = 'MyFile.docx';
$objWriter->save($filename);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
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($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;
This is work for me:
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007', $download = true);
header("Content-Disposition: attachment; filename='File.docx'");
$objWriter->save("php://output");
now whit Ver 0.13.0
https://github.com/PHPOffice/PHPWord
<?
require_once "../include/PHPWord-develop/bootstrap.php";
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
$templateProcessor->setValue('var01', 'Sun');
$templateProcessor->setValue('var02', 'Mercury');
//#####################################################
// Save File
//#####################################################
//#####################################################
header("Content-Disposition: attachment; filename='output01.docx'");
$templateProcessor->saveAs('php://output');
//#####################################################
//#####################################################
?>
A simple solution for Laravel based on #user3214824 answer.
// ...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$doc_name = 'fileName.docx';
$objWriter->save($doc_name); // saving in the public path just for testing
return response()->download(public_path($doc_name))->deleteFileAfterSend(true);
Sorry this came in later. I stumbled on this while trying to solve the same problem. I was able to get it working on Laravel 5 using below:
$file_dir = $template_upload_dir.DIRECTORY_SEPARATOR.'filename.docx';
$tags = array();
if (file_exists($file_dir)) {
$templateProcessor = new TemplateProcessor($file_dir);
$tags = $templateProcessor->getVariables();
$replace = array('');
$templateProcessor->setValue($tags, $replace);
$save_file_name = $fullname.'-'.$inv_code.'-'.date('YmdHis').'.docx';
$templateProcessor->saveAs($save_file_name);
return response()->download($save_file_name)->deleteFileAfterSend(true);
}
Hope it helps someone!!!
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
header("Content-Disposition: attachment; filename='myFile.docx'");
$objWriter->save("php://output");