Search code examples
phpfilefilenamestemp

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?


Solution

  • 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
    }