如何创建具有特定名称的临时文件

Ale*_*lex 3 php filenames file temp

我想创建一个临时文件,在脚本以特定文件名结尾删除自己.

我知道tmpfile()"自动删除"功能,但它不会让你命名文件.

有任何想法吗?

Mav*_*ick 6

如果要创建唯一的文件名,可以使用tempnam().

这是一个例子:

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

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

unlink($tmpfile);
Run Code Online (Sandbox Code Playgroud)

更新1

临时文件类管理器

<?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
}
Run Code Online (Sandbox Code Playgroud)