我想创建一个临时文件,它会在脚本以特定文件名结束时自行删除。
我知道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
}