From fpdf.org
- Use a redirection technique. It consists in generating the PDF in a temporary file on the server and redirect the client on it (by using JavaScript, not the Location HTTP header which also causes trouble). For instance, at the end of the script, you can put the following:
//Determine a temporary file name in the current directory
$file=basename(tempnam(getcwd(),'tmp'));
//Save PDF to file
$pdf->Output($file);
//JavaScript redirection
echo "<HTML><SCRIPT>document.location='getpdf.php?f=$file';</SCRIPT></HTML>";
Then create the getpdf.php file with this:
<?php
$f=$HTTP_GET_VARS['f'];
//Check file (don't skip it!)
if(substr($f,0,3)!='tmp' or strpos($f,'/') or strpos($f,'\\'))
die('Incorrect file name');
if(!file_exists($f))
die('File does not exist');
//Handle special IE request if needed
if($HTTP_SERVER_VARS['HTTP_USER_AGENT']=='contype')
{
Header('Content-Type: application/pdf');
exit;
}
//Output PDF
Header('Content-Type: application/pdf');
Header('Content-Length: '.filesize($f));
readfile($f);
//Remove file
unlink($f);
exit;
?>
This method works in most cases but IE6 can still experience trouble. The "ultimate" method consists in redirecting directly to the temporary file. The file name must therefore end with .pdf:
//Determine a temporary file name in the current directory
$file=basename(tempnam(getcwd(),'tmp'));
rename($file,$file.'.pdf');
$file.='.pdf';
//Save PDF to file
$pdf->Output($file);
//JavaScript redirection
echo "<HTML><SCRIPT>document.location='$file';</SCRIPT></HTML>";
This method turns the dynamic PDF into a static one and avoids all troubles. But you have to do some cleaning in order to delete the temporary files. For instance:
function CleanFiles($dir)
{
//Delete temporary files
$t=time();
$h=opendir($dir);
while($file=readdir($h))
{
if(substr($file,0,3)=='tmp' and substr($file,-4)=='.pdf')
{
$path=$dir.'/'.$file;
if($t-filemtime($path)>3600)
@unlink($path);
}
}
closedir($h);
}
This function deletes all files of the form tmp*.pdf older than an hour in the specified directory. You may call it where you want, for instance in the script which generates the PDF.
Remark: it is necessary to open the PDF in a new window, as you can't go backwards due to the redirection.