Reputation: 44
I have written a PHP templating engine for parsing text into valid php code before executing. Currently I keep of this file in memory then eval()
after parsing into valid php code. After researching more on the evils of using eval()
with user input I have found it wiser to write the parsed content to a file and then include
the file. I am using tmpfile()
function for this. So far it doen not work, besides, I dunno where this temporary file is created and I would not like my template parser loitering files anyhow on a user's filesystem. I would like to have this temp file created in the same directory as resides the template parser class.
Now, problem is, tmpfile()
does not take any parameter as shown here http://php.net/manual/en/function.tmpfile.php .
Below is my template parser class
<?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
}
}
I need to know the file path because I want to be sure that I don't leave garbage even in case of a fatal error, or killed process by calling unlink($tmp_file_path)
Any ideas on how to define a dir for tmpfile()
during this script execution only? I will appreciate.
Upvotes: 1
Views: 2594
Reputation: 1558
The tmpfile()
function creates file in the system's TMP
dir. Where it is you can get with sys_get_temp_dir()
.
Some more control gives you tempnam()
. But don't forget to cleanup after yourself.
If you use tmpfile()
you don't have to delete the file manually. According to documentation:
The file is automatically removed when closed (for example, by calling
fclose()
, or when there are no remaining references to the file handle returned bytmpfile()
), or when the script ends.
To include
the content of the file you can try following:
$filename = tempnam(sys_get_temp_dir());
// create content with fopen(), fwrite(), fclose()
include $filename;
unlink($filename);
I would suggest to use instead some kind of modern templating libraries like Smarty or Twig
Upvotes: 1