Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a temp file with a specific name

I would like to create a temp file which deletes itself on script ending with a specific filename.

I know tmpfile() does the "autodelete" function but it doesn't let you name the file.

Any ideas?

like image 426
Alex Avatar asked Mar 15 '23 22:03

Alex


1 Answers

If you want to create a unique filename you can use tempnam().

This is an example:

<?php
$tmpfile = tempnam(sys_get_temp_dir(), "FOO");

$handle = fopen($tmpfile, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

unlink($tmpfile);

UPDATE 1

temporary file class manager

<?php
class TempFile
{
    public $path;

    public function __construct()
    {
        $this->path = tempnam(sys_get_temp_dir(), 'Phrappe');
    }

    public function __destruct()
    {
        unlink($this->path);
    }
}

function i_need_a_temp_file()
{
  $temp_file = new TempFile;
  // do something with $temp_file->path
  // ...
  // the file will be deleted when this function exits
}
like image 105
Maverick Avatar answered Mar 29 '23 18:03

Maverick