Saving file generated by AJAX script
Good evening.
I am using Yii framework and mPDF library to generate some PDFs via Ajax script and I need to force "save as" dialog in users browsers.
I know how to solve this problem when one user uploads one file. Does anyone have a hint on how I can get this all to work on a high load system (e.g. multiple users trying to create and download a PDF will try to access the same temporary file, which will throw an error)?
Should I generate a separate file for each session? And how would it be good to clean up these temporary files?
Thank you for your help.
source to share
you have to use tempnam
http://www.php.net/manual/en/function.tempnam.php to create temporary files. they will be uniquely named so it will be easy to do one per session. Just uninstall as usual when you're done with them.
source to share
Make an invisible iframe. From JS, set the iframe src to a script on your server that generates the PDF.
<iframe src="http://yoursite.com/download-file.php?report=pdf¶m1=value1¶m2=value2..." width="1" height="1"></iframe>
Then (and I'm not sure how you do it with mPDF), one has to point the file from the script directly to the browser. It's something like this:
<?php
$x = some_function($_GET['param1'],$_GET['param2', ...); // PDF GEN. ROUTINE, BASED ON REQUEST DATA, HOWEVER YOU DO IT
header('Content-type: application/pdf');
echo $x;
This should solve all your problems.
source to share
First of all, I would recommend that you create a different temporary file for each generated PDF, to avoid any possible error, like one user downloading some other PDF, etc.
To clean up the temp directory, I would use a cronjob, which removes all files older than N days.
To "force the dialog to be saved" you must set the title Content-disposition
to attachment
:
header('Content-Disposition: attachment; filename="myfile.pdf"');
source to share