<?php
eval("if (1==1){");
echo ('abc');
eval("}");
?>
Then i get a error :
Parse error: parse error in C:\wamp\www\test\index.php(2) : eval()'d code on line 1
abc
Parse error: parse error in C:\wamp\www\test\index.php(4) : eval()'d code on line 1
How to fix?
You should really try to avoid using eval if at all possible. It presents an enormous and nearly unsurmountable security risk. I have never in my career come across a good reason to use this function. If you post an example, maybe we can help you find a way to accomplish your goal without this immense risk.
Disclaimer aside, I think the issue is that you're starting an expression in the eval that needs to be complete.
You could try this instead:
<?php
$test = eval("return 1==1;");
if($test)
{
echo 'abc';
}
edit:
The goal is to do something like this:
[if {expression}][blog_title][endif]
Here is an idea. Instead of allowing the user to enter any expression, just use a variable, which the user can set. For example:
[if should_show_blog_title][blog_title][endif]
Then, the user could do this (pseudo-ish code, since I'm not sure what your templating API looks like):
$template = new Template();
// shows blog title
$template->set_variable('should_show_blog_title', 1 == 1); // 1 == 1 is true, so the variable is true
$template->set_variable('blog_title', 'Awesomesauce Blog!');
// doesn't show title
$template->set_variable('should_show_blog_title', 1 == 0); // 1 == 0 is false, so the variable is false
$template->set_variable('blog_title', 'Awesomesauce Blog!');
Another idea would be to provide a limited number of operators or functions that the user could use. Instead of evaling it, you have to parse it. For example:
[if not_empty(blog_title)][blog_title][end if]
Then when you parse and compile the template (insert the data in, basically), you look for these special functions and translate them in to PHP. This is basically whitelisting, since you're only letting the user perform a very restricted subset of functionality.
You should look at Mustache, which kind of follows the first idea. The implementation is actually pretty simple. The PHP implementation of mustache is here: mustache.php. You could look through the samples and some code to see if you could get some ideas.
One thing to keep in mind, is that if you're evaling, the templating engine isn't going to be as user-friendly, because then the user has to write valid PHP in their conditions. Part of the appeal of mustache is that it's so simple and incredibly easy to use. I'm an experienced PHP developer, and while I can hack in PHP all day long, I still prefer mustache for templating because it just lets me get to the point.
Simple ...
<?php
eval(
"if (1==1){".
"echo ('abc');".
"}");
?>
Things in eval('...') must be a self completed expression or statement and '}' is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With