Sometimes I need to create PHP code for formatting arrays on the fly. one way to do this is to use eval. but I think of writing the generated code to a PHP file and then include it. This has many advantages to eval, one of them is caching of generated code. But I haven’t seen such a practice in other code. I don’t know if there’s any problem regarding security or other things with this?
This is an example:
<?php
$code = '<? foreach($rows as $row) {$row["insertion"] = format($row["insertion"]);} ?>'
file_put_contents('formatter.php', $code);
include('formatter.php');
?>
I just want to know is it good to create a PHP file on the fly and then include it?
Or is it better to just go ahead and eval() the code directly, with no stored history?
If you have to create code dynamically, it is always more efficient and usually more secure to dump the output into a file and then include it. Then you only have to do this once per piece of code and it allows for opcodes caching (via APC and the like) and more efficient preprocessing by the Zend Core engine. ANother benefit is that you can debug included files, while debugging
eval()ed statements is rarely supported.The reason it is more secure to store it into a file is that then you have a record of what was run; with
eval(), it’s more or less a black box and you have no idea what’s been executing. Additionally, you should be able to lock down the writes folder to where only a certain app can write to it. If you separate your dynamic array creation logic from your main app, and then include the file via your main app itself, this will undoubtedly increase security and performance, assuming you’ve made the temp files read-only to Apache and writeable only by the PHP app (doable via cron, among other methods).There’s possibly a better solution for what you’re doing (like memcache or APC fetch/store) but I have run into similar circumstances that largely benefited from the including stuff (for instance, tweaking smarty templates to be included rather than eval’d worked amazingly).