如何使用特定名称创建临时文件

亚历克斯

我想创建一个临时文件,该文件会在以特定文件名结尾的脚本中删除自身。

我知道tmpfile()“自动删除”功能可以,但是它不能让您命名文件。

有任何想法吗?

小牛

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

这是一个例子:

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

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

unlink($tmpfile);

更新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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章