PHPOffice/PHPWord: Download Word documents directly when click download button - php

My code create Word template and instantly download when i run php file.
How to create a button that allow me to create and download word file when i click on it?
Thank you!
<?php
require_once 'vendor/autoload.php';
$phpword = new \PhpOffice\PhpWord\PhpWord();
$ran = time();
$section = $phpword->addSection();
$section->getStyle()
->setPaperSize('Letter')
->setLandscape()
;
$section->addText("Hello World!");
$file = 'test.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$phpword->save("php://output");
?>

You can make a curl request on a php file who create, save the word and return the path, then use js to make a auto-click on a hidden link who you have set the "href=" with the path and have the attribute "download=your_file_name".

Create a tmp folder the same directory youhave the code and add this
objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('tmp/helloWorld.docx');
$file = 'tmp/helloWorld.docx';
if (file_exists($file)) {`enter code here`
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}

Related

PHPWord on server corrupt document with mention of some parts are missing

I have installed PHPWord on my computer with Composer and Wamp64.
using a template, on my computer the template is well modified, and the recording of the file is perfect.
On the infomaniak server, I have a message that the file is corrupted and that there are some parts missing.
I can't find the reason. here is my code.
Please help me find the source of the problem
<?php
$docModele = 'print/modele_cdd_as_2.docx';
require_once '../PhpWord/bootstrap.php';
use\PhpOffice\PhpWord\PhpWord;
// Creating the new document...
$PHPWord = new \PhpOffice\PhpWord\PhpWord();
header('Content-type: application/json; charset=UTF-8');
/* Note: any element you append to a document must reside inside of a Section. */
$document = $PHPWord->loadTemplate($docModele);
$document->setValue('date_debut', $date_debut);
$document->setValue('identite', $identite.' ');
$document->setValue('date_naissance', $date_naissance);
$document->setValue('lieu_naissance', $lieu_naissance);
$document->setValue('dpt_naissance', $dpt_naissance);
$document->setValue('adresse1', $adresse1);
$document->setValue('cp', $cp);
$document->setValue('ville', $ville);
$document->setValue('no_ss', $no_ss);
$document->setValue('jour_debut', $jour_debut);
$document->setValue('date_fin', $date_fin);
$document->setValue('remplace', $remplace);
$document->setValue('motif_txt', $motif_txt);
$document->setValue('essai', $essai);
$document->setValue('indice', $indice);
$document->setValue('valeur_point', $valeur_point);
$document->setValue('brut', $brut);
$document->setValue('majoration', $majoration);
$document->setValue('date_contrat', $date_contrat);
//XML Writer compatibility
\PhpOffice\PhpWord\Settings::setCompatibility(false);
//#####################################################
// Save File
//#####################################################
//#####################################################
ob_clean();
$filename = 'nom_du_fichier.docx';
header("Content-Disposition: attachment; filename=$filename");
$document->saveAs('php://output');
//#####################################################
//#####################################################
exit;
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
// création du fichier
$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));
ob_clean();
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
?>

PHP - Forcing download a file not working

code.php
$code = $_GET["code"];
$file = 'code/'.$code.'.html';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Generated URL to download the file:
http://www.example.com/code.php?code=yoursite.com_nbsp63ibrf
Well, I want to forcing download the html file, above code not working and it just preview the file at browser!
file_exists() returns false. Change your path with document root:
$code = $_GET["code"];
$file = $_SERVER['DOCUMENT_ROOT'] . '/code/' . $code . '.html'; // set your path from document root.
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Try changing the content type to match the file type and setting the transfer encoding to binary:
header('Content-Transfer-Encoding: binary');
header('Content-Type: text/html');
Try this
$code = $_GET["code"];
$file = $_SERVER['DOCUMENT_ROOT'] . '/code/' . $code . '.html'; // set your path from document root.
if (file_exists($file)) {
header("Content-Type: text/html");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
unfortunately it was a encoding issue. I changed code.php encoding from UTF-8 to UTF-8 Without BOM then problem solved. Thanks for all answers and helps. I forgot that PHP header only works with UTF-8 Without BOM.
This is actually not possible.
The browser can always decide on its own, if the file should be downloaded or not.
The furthest you can go is sending the content-disposition header.

Nothing gets printed in the doc using PHPWord

I am using PHPWord to download docx files in php. But nothing gets printed in the file if I try to download it. But the contents get displayed in the file which gets saved on the server. Below is the code which I have used. Can anyone please tell me what the issue is.
<?php
include "../includes/config.inc.php";
include '../PHPWord.php';
// Create a new PHPWord Object
$PHPWord = new PHPWord();
// Every element you want to append to the word document is placed in a section. So you need a section:
$section = $PHPWord->createSection();
$section->addText('CANDIDATES DETAILS');
$filename='test';
$file=$filename.'.docx';
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('/form_doc/'.$filename.'.docx');
//download the file
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
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($file));
readfile($file);
Thanks in advance.
Regards,
Neha
Your should set path to file to readfile() and filesize() functions:
$file = $filename.'.docx';
$filepath = '/form_doc/' . $file;
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save($filepath);
//download the file
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
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($filepath));
readfile($filepath);

Force Downloading file through php not working

I was trying to write a script through which user can download the image directly.
Here is the code i end up with,
<?php
$fileContents = file_get_contents('http://xxx.com/images/imageName.jpg');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.urlencode("http://xxx.com/images/imageName.jpg"));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileContents));
ob_clean();
flush();
echo $fileContents;
exit;
?>
But everytime i hit the url for the above script in the browser it returns a file with zero byte data.
would you like to help me to resolve this problem ?
Try the code below
<?php
$file_name = 'file.png';
$file_url = 'http://www.myremoteserver.com/' . $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_url);
?>
Read more , Read this tutorial too
I notice that you use filesize on the contents of the file instead of at the filename itself;
Your code would work if it was:
<?php
$filename = 'http://xxx.com/images/imageName.jpg';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.urlencode($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean(); // not necessary
flush(); // not necessary
echo file_get_contents($filename); // or just use readfile($filename);
exit;
?>

file corrupt when click download link

I try to use php to force the image jpg file download, I have implemented eth following code:
html
<a href = "filedownload.php?src=uploads/myimage.jpg&download=true>download this file</a>
download.php
<?php
ob_start();
include_once 'functions.php';
if (isset($_GET['download']) && $_GET['download'] == 'true')
{
$src = sanitizeString($_GET['src']);
header('Content-Description: File Transfer');
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename='.basename($src));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: public');
header('Pragma: public');
}
?>
Suppose the full path of the image is "www.example.com/smith/topic/uploads/myimage.jpg", I have recieved the right image name and the download window is appeared as well, but the image is corrupt and with 1KB size, any one could tell me why, thanks a lot.
Here you are example how to use readfile function
<?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;
}
?>
You need some code that actually sends over the file. See e.g. readfile or fpassthru
Try to use:
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );

Categories