tags:

views:

151

answers:

6

I am trying to figure out how does eval() function works in a simple way. I tried the following code but it doesn't work, instead it shows up a parse error.

<?php
    $str = "exit()";
    eval($str);
?>

What's wrong with my code ?

+1  A: 

needs a semicolon i think

<?php
    $str = "exit();";
    eval($str);
?>

From the PHP docs:

Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval()

echo
Thanx a lot. That tutorial http://www.tuxradar.com/practicalphp/4/4/0 just confused me a little.
ta.abouzeid
+2  A: 

Just a tip - eval'ed code is evaluated dynamically and can evade the garbage collector.

Jeff Ober
That's hardly the biggest problem with eval. :)
Greg Hewgill
A: 

$str = "exit();"; may work. eval() should not be used, except when really necessary.

Also, try using a function other than exit(), or pass a string as an argument to the exit function. Otherwise, you won't see an output from it.

Mauricio
I was just trying to follow that tutorialhttp://www.tuxradar.com/practicalphp/4/4/0It was mentioned there without a semicolon that's why I got confused.
ta.abouzeid
+1  A: 

How to use eval function in PHP ?

If you can help it: Not at all.

I am only half joking :)

Pekka
Sorry the question was wrong :D I am not a native English speaker so i make mistakes.
ta.abouzeid
No, your question was completely o.k. and fine english. I was referring to the fact that eval() is generally regarded as bad practice and should be avoided.
Pekka
Oh sorry I misunderstood. I got your point, thanx
ta.abouzeid
+1  A: 

Is the error: "Parse error: syntax error, unexpected $end in Command line code(1)"? If so, that is because you didn't put semicolon at the end of exit().

So try:

<?php
    $str = "exit();";
    eval($str);
?>

Hope this helps.

NawaMan
+1  A: 

It needs a semicolon at the end:

and the problem with eval is that it calls the parser from a IL language, thus, the evalued code would be a VSL(very slow language), so, if your website won't be hit by many users at same time, then its no problem, but if you are projecting something big, then I suggest you not use eval, only in really necessary case.

hope it helps.
Joe

Jonathan