taabouzeid
taabouzeid

Reputation: 939

How does eval function work in PHP?

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 ?

Upvotes: 0

Views: 1724

Answers (5)

Jonathan
Jonathan

Reputation: 4928

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

Upvotes: 1

NawaMan
NawaMan

Reputation: 25687

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.

Upvotes: 2

Mauricio
Mauricio

Reputation: 387

$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.

Upvotes: 0

Jeff Ober
Jeff Ober

Reputation: 5027

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

Upvotes: 2

echo
echo

Reputation: 7875

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()

Upvotes: 4

Related Questions