PHP create random tmp file and get its full path

40,678

Solution 1

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

See this example.

Solution 2

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.

Share:
40,678

Related videos on Youtube

Farzher
Author by

Farzher

i.write(code);

Updated on July 09, 2022

Comments

  • Farzher
    Farzher almost 2 years

    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?

  • AndreKR
    AndreKR almost 8 years
    In the original code the file is removed when the script exits/crashes. This one leaves garbage behind. See @bishop's answer for the proper solution.
  • tim
    tim over 6 years
    The first parameter for directory is not taken into consideration on Windows platfors. Which always uses C:\Windows\Temp\.