我已经编写了一个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()
定义目录,有什么想法吗?我会很感激的。
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);
我建议使用一些现代模板库,如Smarty或Twig