note 102729 deleted from function.php-check-syntax by danbrown

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: luke at cywh dot com 

----

nicolas dot grekas+php at gmail dot com has a great idea using an if block as a sandbox with eval for syntax checking. But it's important to note that if/when someone does break the if block code WILL be executed. That's why it's better to add "return TRUE;" to the very top. 

(Nicolas used token_get_all to balance braces. But from a security standpoint it's better not to leave out any possibility.)

What the if block does is makes function/class blocks conditional, which means they are not defined in the current scope.

What you should do is combine both techniques:

<?php

var_dump(eval("return TRUE; if(TRUE): ".$code." endif;"));

?>

If you use the alternative control structure syntax you don't even have to track braces (just look for another "endif;"). The alternative syntax isn't commonly used.

If someone does break the if block or any additional checking is bypassed the execution gets stopped at the return.

I use this technique to make sure an expression is valid for my template system. It's important to note that I don't use this alone: I use token_get_all to construct the template syntax (which isn't completely PHP's syntax). Using token_get_all I ensure that variable functions are forbidden, and only allowed functions can be used. I use the eval sandbox to simply ensure tokens are in a logical order.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.