Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP create random tmp file and get its full path

After I do:

$temp = tmpfile(); fwrite($temp, "writing to tempfile"); 

I'd like to get a full path to the $temp file that tmpfile has created.

What do I need to do to get that information?

like image 816
Farzher Avatar asked May 10 '13 16:05

Farzher


People also ask

What is tmp file returns?

The tmpfile() function returns a stream pointer, if successful. If it cannot open the file, it returns a NULL pointer. On normal end ( exit() ), these temporary files are removed. On the Data Management system, the tmpfile() function creates a new file that is named QTEMP/QACXxxxxxx.

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.

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.


2 Answers

tmpfile returns a stream-able file pointer.

To get the corresponding path, ask the stream for its meta data:

$file = tmpfile(); $path = stream_get_meta_data($file)['uri']; // eg: /tmp/phpFx0513a 

The benefit of the tmpfile approach? PHP automatically removes the $path when $file goes out of scope. With tempnam, you must manually remove the created file.

like image 79
bishop Avatar answered Oct 02 '22 12:10

bishop


$path = tempnam(sys_get_temp_dir(), 'prefix'); 

See this example.

like image 21
Alix Axel Avatar answered Oct 02 '22 11:10

Alix Axel