Fixed DOMPDF File Permission Issues -- Guess How

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
volomike
Forum Regular
Posts: 633
Joined: Wed Jan 16, 2008 9:04 am
Location: Myrtle Beach, South Carolina, USA

Fixed DOMPDF File Permission Issues -- Guess How

Post by volomike »

I had the strangest thing occur today and the next time you use tempnam, rename, and/or DomPDF -- this perhaps might affect you. I was migrating a project from a non-MVC framework to an MVC one. (That's irrelevant -- just note that I had this working, previously.) In the old one, I was using DomPDF like it said in the README for it -- you render (not display) your HTML into a string, create a temporary file with tempnam, rename your temp file with a filename you like better, and then use DomPDF to stream into it. There's an extra step in there regarding setting up DomPDF, but that's irrelevant.

The problem I was getting was where DomPDF would generate an error. It would say:

Warning: rename(/tmp/pdf-GHr8tf,volomike-495-194207.pdf) [function.rename]: Permission denied in /var/www/mysite.com/controllers/Users/PDF.php on line 311
Unable to stream pdf: headers already sent

The rename command was bombing because it was tried to rename a file that had permission denied. And by spitting out this error, the DomPDF stream method was failing because an error means that headers have already been sent. The fix was for me to turn errors off, but I didn't want to do that because then I wouldn't know if something else was wrong -- I'll do that when we go into production on this particular task.

The fix? Yeah, I had to do this (relevant parts bolded):

$sTempFile = @ tempnam('/tmp','pdf-');
$sNewName = $sOnlyAlphaLastName . '-' . mt_rand(111,999) . '-' . gmdate('His') . '.pdf';
@ rename($sTempFile, $sNewName);

See the @ symbols? Yeah -- that fixed it. And, remarkably, the file was renamed properly because I checked the /tmp folder and saw that it was.

Long story short -- if you create a temp file with tempnam() and then want to rename it, and get a permission denied error, just stick @ in front of both functions and it might fix you. However, this has repercussions such as the fact you might be out of disk space, or may have some sort of jail root problem where your web app process has no power in /tmp, or something else funky going on. So, you'll want to do some error checks on that, perhaps.

Hope this helps you, because it was mind boggling and hair pulling time for me for awhile until I tried this.
Post Reply