如何在PHP中为临时文件指定目录?

时间:2016-01-04 08:35:15

标签: php function file class temporary-files

我已经编写了一个PHP模板引擎,用于在执行之前将文本解析为有效的PHP代码。目前我在解析成有效的PHP代码之后将此文件保留在内存中eval()。在研究了使用eval()用户输入的弊端后,我发现将解析后的内容写入文件然后include文件更明智。我正在使用tmpfile()函数。到目前为止,它不起作用,此外,我不知道这个临时文件的创建位置,我不喜欢我的模板解析器无论如何在用户的文件系统上闲置文件。我想在与模板解析器类相同的目录中创建此临时文件。 现在,问题是tmpfile()没有采用此处显示的任何参数http://php.net/manual/en/function.tmpfile.php。 下面是我的模板解析器类

<?php
class TemplateParser {

  //this method renders template file
  public function render($file_path)
  {
    #...code to compile contents

    //create temporary file and store handle
    $file_handler = tmpfile();

    //write contents to tmpfile()       
    fwrite($file_handler,$compiled_template_file_contents);

    //close opened file
    fclose($file_handler);

    //include the file into the current script
    include $file_handler; //this doesn't work, now what works?? coz this is not a valid filepath but a resource

  }

}

我需要知道文件路径,因为我想确保即使出现致命错误也不会留下垃圾,或者通过调用unlink($tmp_file_path)来杀死进程。有关如何定义目录的任何想法仅在此脚本执行期间tmpfile()?我将不胜感激。

1 个答案:

答案 0 :(得分:1)

tmpfile()函数在系统的TMP目录中创建文件。你可以通过sys_get_temp_dir()来获得它。

更多控件会为您提供tempnam()。但不要忘记自己清理。

如果您使用tmpfile(),则无需手动删除该文件。根据文件:

  

关闭时会自动删除该文件(例如,通过调用fclose(),或者对tmpfile()返回的文件句柄没有剩余引用),或者脚本结束时。

include您可以尝试以下文件的内容:

$filename = tempnam(sys_get_temp_dir());

// create content with fopen(), fwrite(), fclose()

include $filename;

unlink($filename);

我建议使用某种现代模板库,例如SmartyTwig