Creating a temporary file with the extension .pdf php tempnam

Is it possible to create a .pdf file extension using tempname? I need to send an email with a file created using tempname. (I can send the file, but I need the extension .pdf)

+4
source share
4 answers

You can specify the file name in the MIME header in a multi-page message.

+1
source
$tempname = tempnam('', 'report_'); rename($tempname, $tempname .= '.pdf'); var_dump($tempname, is_file($tempname)); 
+3
source

No, this is not possible with tempnam. You will need to write your own function for this, for example, using the current time. The problem here is to avoid race conditions, but this can be resolved by including the PID in the file name, for example:

 do { $filename = rand(); $filename .= '.'. str_replace(' ', '.', microtime()); $filename .= '.'. getmypid(); $filename .= '.pdf'; } while(file_exists($filename)); 

If the directory is shared between different machines, the PID is not guaranteed to be unique. In this case, also specify the host name of the current computer (as specified by gethostname).

0
source

I use this function for temporary unique names:

 function tempnam_sfx ($path, $suffix) { if(!is_dir($path)){ mkdir($path, 0777, true); } do { $file = $path . DIRECTORY_SEPARATOR . mt_rand () . $suffix; } while (file_exists($file)); return $file; } 
0
source

All Articles