if (file_exists("folder/$unique_id.pdf")) {
header('Content-type: application/pdf');
ob_clean(); // Added after reading similar question's answer
flush(); // Added after reading similar question's answer
readfile("folder/$unique_id.pdf");
} else {
$html = "PLACING_MY_HTML_CODE_HERE";
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper("A4");
$dompdf->render();
$output = $dompdf->output();
file_put_contents("folder/$unique_id.pdf", $output);
header('Content-type: application/pdf');
ob_clean(); // Added after reading similar question's answer
flush(); // Added after reading similar question's answer
readfile("folder/$unique_id.pdf");
}
If the PDF file does not exist, the PDF files is generated using DOMPDF. The files is generated without any error and stored inside the folder. But sometimes, instead of reading the generated file, it downloads a file without extension and mostly with name 'download'. I tried opening the file in text editor, and I see symbols with some headers such as application
, content-type
etc.
Later, searched in SO and saw this question, and added ob_clean
, flush
in my code. But still the issue persists.
Note: I checked opening the PDF file stored in the folder using Adobe reader and Google Chrome. The files were completely rendered and saved properly.
EDIT:
Instead of readfile
I tried header
redirect directly to the file. And there are no issues with this.
Any suggestions?