6 January 2006
I used eval() today
Just as self-diagnosis is frowned upon in the medical world, I hesitate to say that my use of eval() was approriate. I’ve been working on a library to transcode HTML into another format, and it became neccessary to support PHP in addition to static HTML. I couldn’t dump to the shell and execute the file from there because the page-in-question accesses data in $_SESSION. I couldn’t just include it and capture its output through output buffering because of the way PHP handles relative paths in included files. The files were far too complex to even consider implicit evaluation. The only other option would to output-buffer the file itself, spawn a web-request to it, dump its output to a temporary file and process that. Nevermind the difficulty of getting the session correct, the file management for that solution is obscene. Which leaves eval(). So I now have the following code to handle it:
ob_start();
eval("?>$strCode<?");
$strCode = ob_end_clean();
Basically, I’m using eval to fork PHP and execute a file stored in memory. PHP puts an implicit <? ?> around the code passed to it, so I have to undo that to prevent puking on raw HTML.
If there’s another way, I’d sure like to know. My solution works, but its quite ugly, non-intuitive and I’m not proud of it. But I need to do it somehow, so c’est la vie.

