Change saving directory in phpspreadsheet - php

Im using PhpSpreadsheet to generate XLS files, all the functions work perfect except that it saves local files in temporary directories and I want to save them in a specific folder.
use PhpOffice\PhpSpreadsheet\IOFactory;
require __DIR__ . '/Header.php';
$spreadsheet = require __DIR__ . '/templates/MyTemplate.php';
$filename = $helper->getFilename("MyFilename", 'xls');
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
$callStartTime = microtime(true);
$writer->save($filename);
$helper->logWrite($writer, $filename, $callStartTime);
But the output is located in
Write Xls format to /var/folders/pn/lyj970q90lq20mjv39bpgx_80000gn/T/phpspreadsheet/MyFilename.xls in 0.0640 seconds
Is there an other function to set the saving directory I want the files in?

Use dot in path
$writer->save("./templates/MyFilename.xls");

On this line:
$filename = $helper->getFilename("MyFilename", 'xls');
Change to:
$filename = basename($helper->getFilename("MyFilename", 'xls'));
This way, $filename will only contain the file name. Then you can insert your path and make it work as you want, as I did with mine:
$writer->save('C:/xampp/htdocs/tmp/' . $outputFileName);

Make sure these lines are commented out. Since this parameter will tell the server to export Xlsx as downloadable file. Not in specific custom location.
// Redirect output to a client’s web browser (Xlsx)
// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// header('Content-Disposition: attachment;filename="'.$FileName.'"');
// header('Cache-Control: max-age=0');
// // If you're serving to IE 9, then the following may be needed
// header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
// header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
// header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
// header('Pragma: public'); // HTTP/1.0
And finally you can save your file :
$writer->save("Location/Of/YourFolder".$YourFileName);

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
source
https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#redirect-output-to-a-clients-web-browser

Related

How to force download zip file in codeigniter

I am trying to create a simple digital store web application using codeigniter.
I would like to use the force download helper function so that the real url of the file will not be known by the user.
I tried following the documentation in the codeignter - it works but the file get corrupted.
Here is my code
//* Get the website name
$site = $this->Settings_model->getApllicationInfo();
$sitename = $site->set_site_name;
//* Prepare file for downloading
$filename = $sitename.'-'.$item_info->item_id.'-'.$item_info->item_name;
$locate = './static/files/zips/'.$file;
force_download($locate, $filename);
It downloads the file but it get broken please help me or give me any other suggestion I can use.
Use below function to download the file
function auto_download($path, $name) {
if(is_file($path)) {
if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
$this->load->helper('file');
$mime = get_mime_by_extension($path);
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($path)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($name).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path));
header('Connection: close');
readfile($path);
exit();
}
}
I hope you are using file extension on the filename you supply for the first argument to force_download(). Because Codeigniter uses MIME-type. I hope it will work for you

PHPExcel export not working : displays "the website cannot be reached"

I have cloned a project from server and installed in my local setup.
I am trying to export excel file to the browser using PHPExcel. It is working fine in the server. But there is problem with the local setup.
Also I checked number of columns and fields and they are fine.
Below is the code:
<?php
//PHPExcel starts from here
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Kathmandu');
if (PHP_SAPI == 'cli')
die('Error in loading PHPExcel');
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("GBD Admin")
->setLastModifiedBy("GBD Admin")
->setTitle("Weekly checkin/checkout log")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("Checkin/Checkout Logs")
->setCategory("Checkin/Checkout Logs");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Date of Export')
->setCellValue('B1', $now)
->setCellValue('A3', 'Employee Name')
->setCellValue('B3', ' Checkin-date')
->setCellValue('C3', ' Checkin-time')
->setCellValue('D3', ' Checkout-date')
->setCellValue('E3', ' Checkout-time')
// ->setCellValue('F3', ' Total-time Spent')
// ->setCellValue('G3', ' Over-time')
->setCellValue('F3', ' Early checkout-remarks')
->setCellValue('G3', ' Late checkin-remarks');
// Newly added statement below
// ->setCellValue('H3', ' Absent/Leave Remarks');
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A3:H3')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->fromArray($results, null, 'A5');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(45);
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Login-data-' . $now);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Login_data_' . $now . '.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
I have been getting this error:
This site can’t be reached
The webpage at http://localhost/gbdportal-new/Export might be
temporarily down or it may have moved permanently to a new web
address. ERR_INVALID_RESPONSE
It is working fine with the live version currently running on the server. What could be the problem?
This is a bug in phpExcel in combination with php7:
https://github.com/PHPOffice/PHPExcel/issues/716
on Line 581 of file PHPExcel/Classes/PHPExcel/Calculation/Functions.php there is a " break" , simply comment.

PHP readfile with PHPPowerpoint issue

I am using PHPPowerpoint to create a pptx file with some charts, and have no problem storing it in the same folder as the PHP script. PHPPowerpoint does that on itself.
I want to download the pptx file after it has been created, and so far I have tried every option I could locate on the web. This is how i try to do it atm.:
$file = str_replace('generate_report.php', 'export_download.pptx', __FILE__);
header('Content-Description: File Transfer');
header('Content-disposition: attachment; filename="' . $file . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
header('Expires: 0');
header('Cache-Control: ');
header('Pragma: ');
flush();
ob_clean();
readfile($file);
Nothing is downloaded when I execute the script. My pptx is created on the server and I can open it, no problem. But it wont download the file. I got the content type from this thread: What is a correct mime type for docx, pptx etc?. I also tried with many other types. When I console log my response i get a weird string (very long), beginning like this: PKCTDD����[Content_Types].xml͗�n�0E�|E�-J��*�X�����+���m���wBhE
Also tried this:
$handle = fopen($file, 'rb');
$buffer = '';
while (!feof($handle)) {
$buffer = fread($handle, 4096);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
Anybody who can help?
The following headers should work; and it's also better streaming directly to php://output rather than save to disk file and then spooling that disk file to the browser
// Redirect output to a client’s web browser
header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
header('Content-Disposition: attachment;filename="' . $file . '"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPPowerPoint_IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
$objWriter->save('php://output');

correct PHP headers for pdf file download

I'm really struggling to get my application to open a pdf when the user clicks on a link.
So far the anchor tag redirects to a page which sends headers that are:
$filename='./pdf/jobs/pdffile.pdf;
$url_download = BASE_URL . RELATIVE_PATH . $filename;
header("Content-type:application/pdf");
header("Content-Disposition:inline;filename='$filename");
readfile("downloaded.pdf");
this doesn't seem to work, has anybody successfully sorted this problem in the past?
Example 2 on w3schools shows what you are trying to achieve.
<?php
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename=\"downloaded.pdf\"");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
Also remember that,
It is important to notice that header() must be called before any
actual output is sent (In PHP 4 and later, you can use output
buffering to solve this problem)
$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
There are some things to be considered in your code.
First, write those headers correctly. You will never see any server sending Content-type:application/pdf, the header is Content-Type: application/pdf, spaced, with capitalized first letters etc.
The file name in Content-Disposition is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in " not '. Also, your last ' is missing.
Content-Disposition: inline implies the file should be displayed, not downloaded. Use attachment instead.
In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)
All that being said, your code should look more like this:
<?php
$filename = './pdf/jobs/pdffile.pdf';
$fileinfo = pathinfo($filename);
$sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);
header('Content-Type: application/pdf');
header("Content-Disposition: attachment; filename=\"$sendname\"");
header('Content-Length: ' . filesize($filename));
readfile($filename);
Technically Content-Length is optional but it is important if you want the user to be able to keep track of the download progress, and detect if the download was interrupted before the end. When using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php or after ?>, not even an empty line.
I had the same problem recently and this helped me:
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("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
Can you try this, readfile need the full file path.
$filename='/pdf/jobs/pdffile.pdf';
$url_download = BASE_URL . RELATIVE_PATH . $filename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($filename)."'");
header('Content-Length: ' . filesize($filename));
header("Cache-control: private"); //use this to open files directly
readfile($filename);
You need to define the size of file...
header('Content-Length: ' . filesize($file));
And this line is wrong:
header("Content-Disposition:inline;filename='$filename");
You messed up quotas.
header("Content-type:application/pdf");
// It will be called downloaded.pdf thats mean define file name would be show
header("Content-Disposition:attachment;filename= $fileName ");
// The PDF source is in original.pdf
readfile($file_url);

Force file download in php

I have built a simple file manager where users can download any type of file such as pdf, word or gif files. I want all of them to download file rather than view it in browsers. The uploaded filenames are stored in database.
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
http://php.net/manual/en/function.header.php
You can use the "Content-Disposition" header for that:
header("Content-Disposition: attachment");
The PHP manual provides an excellent example for that.
Normally setting the Content-Disposition to attachment before sending a file force a download by the browser.
You either need to configure your web server to provide this header for the files or send them yourself via PHP, sending a specific header before like :
header('Content-Disposition: attachment; filename=your_file_name.pdf');
Beware that the first solution is better as you won't risk your downloads being cut because the script running time is too long (you could also alter it).
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/pdf;\n");
$len = filesize($filename);
header("Content-Length: $len;\n");
header("Content-Disposition: attachment; filename=\"downfile.pdf\";\n\n");
echo readfile($filename)
source code taken from the TCPDF library
// download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');
}
header('Content-Description: File Transfer');
if (headers_sent()) {
$this->Error('Some data has already been output to browser, can\'t send PDF file');
}
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// force download dialog
if (strpos(php_sapi_name(), 'cgi') === false) {
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);
header('Content-Type: application/pdf', false);
} else {
header('Content-Type: application/pdf');
}
// use the Content-Disposition header to supply a recommended filename
header('Content-Disposition: attachment; filename="'.basename($name).'";');
header('Content-Transfer-Encoding: binary');
$this->sendOutputData($this->getBuffer(), $this->bufferlen);
break;
anyways the most important part is
header('Content-Disposition: attachment; filename="'.basename($name).'";');
and notice that final ; inside the string, without it, it won't work

Categories