Home » Php » PHP create random tmp file and get its full path

PHP create random tmp file and get its full path

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:
$path = tempnam(sys_get_temp_dir(), 'prefix');

See this example.

Answer:

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.