4

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?

Alex
  • 131
  • 2
  • 11
  • 3
    how about this: don't care what the filename is. Or, create a non-temp file by name and delete it yourself. – Drew Aug 29 '15 at 17:23
  • why do you need to have a specific file name ? – mmm Aug 29 '15 at 17:25
  • @Drew If I didn't care about the filename, I wouldn't be asking it in the first place... – Alex Aug 29 '15 at 17:27
  • @mmm Because it needs to be a unique file inside a folder in another server – Alex Aug 29 '15 at 17:28
  • @John It seems there is no way to make this, have you tried making file with `tmpfile()` and copying this as `(tmpfile(), '/foo')` – samayo Aug 29 '15 at 17:34
  • @samaYo yeah. I tried it. It "works" but only after the script ending – Alex Aug 29 '15 at 17:38
  • @Drew But the question I'm asking is WHY there isn't a way to do this properly? – Alex Aug 29 '15 at 17:39
  • @Drew I don't know when it's ending the script – Alex Aug 29 '15 at 17:42
  • @Drew The file needs to be deleted as soon as the script ends. I don't want to do it with cron – Alex Aug 29 '15 at 17:46
  • @Drew Sorry, Maverick gave a posible solution. I think I'll keep it. If you have any other idea I would like to know it :) – Alex Aug 29 '15 at 17:57

1 Answers1

8

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
}
Maverick
  • 905
  • 8
  • 23