Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a temp file with a specific extension using php

Tags:

How do I create a temporary file with a specified extension in php. I came across tempnam() but using it the extension can't be specified.

like image 523
nikhil Avatar asked Jan 23 '12 11:01

nikhil


People also ask

What is tmp file in php?

Definition and Usage. The tmpfile() function creates a temporary file with a unique name in read-write (w+) mode. Note: The file is automatically removed when closed, with fclose() or when the script ends.

How do I create a temp file?

To create and use a temporary fileThe application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.

What is the extension name of temporary file?

Temporary files typically have a . TMP or . TEMP file extension, but any naming convention might be used.

Where does php store TMP files?

php stores all temporary files, that includes uploaded files, in the temporary files directory as specified in the php. ini. Note that for uploads, those files might be removed as soon as the script the file was uploaded to was terminated (so unless you delay that script, you probably won't see the uploaded file).


2 Answers

Easiest way i have found is to create tempfile and then just rename it. For example:

 $tmpfname = tempnam(sys_get_temp_dir(), "Pre_");  rename($tmpfname, $tmpfname .= '.pdf'); 
like image 73
nathan hayfield Avatar answered Sep 22 '22 16:09

nathan hayfield


my way is using tempnam

$file = tempnam(sys_get_temp_dir(), 'prefix'); file_put_contents($file.'.extension', $data); {    //use your file } unlink($file);//to delete an empty file that tempnam creates unlink($file.'.extension');//to delete your file 
like image 23
Yasmany Hernandez Hernandez Avatar answered Sep 21 '22 16:09

Yasmany Hernandez Hernandez