nhanlam
nhanlam

Reputation: 36

I got trouble with eval() function in php?

i have searched this function on google a lot. However, i can't understand this function clearly. i have a example:

<?php
//eval dangerous to use
$motto="lksdfasdkf";
$str= "<h1>Welcome</h1><?php echo $motto;?><br/>"; 
echo $str.'<br />';  //result: welcome
eval("?>"." $str"."<?php echo $motto;");  //error
echo $str;
?>

Upvotes: 0

Views: 52

Answers (2)

Amal
Amal

Reputation: 76656

eval() takes a string and evaluates it as PHP code. Here are some important points to note:

  1. eval() takes PHP Code as it's argument -- not mixed HTML markup. Currently, you're passing a string containing HTML markup.

  2. You don't need to add <?php ... ?> tags in the string. eval() already knows the argument is going to be PHP code (it's supposed to be), so you don't need to tell it

Here's a very short example:

$motto = "lksdfasdkf";    
$str = 'echo $motto;';     
eval($str); // => lksdfasdkf

Here, the string $str contains the literal string echo $motto;, which is a valid statement in PHP. When you call eval($str); the string gets evaluated as PHP code. In this case, it will echo the contents of the variable.

Note that this wouldn't work if you use double-quotes instead:

$motto = "lksdfasdkf";
$str = "echo $motto;"; 
eval($str);

If you have error reporting enabled, then you'll get the following error:

Notice: Use of undefined constant lksdfasdkf - assumed 'lksdfasdkf' in

The reason is that variables are not parsed when they're wrapped in single-quotes. When you use double-quotes to define your variable, the variable value gets interpolated into the resulting string, meaning $str will contain the literal string echo lksdfasdkf; -- which is not valid PHP code. The solution is to escape the dollar character to avoid it being interpreted as a variable:

$motto = "lksdfasdkf";
$str = "echo \$motto;"; 
eval($str); // => lksdfasdkf

Upvotes: 2

Rakesh Sharma
Rakesh Sharma

Reputation: 13738

eval — Evaluate a string as PHP code - your code also working fine

try

$motto="lksdfasdkf";
    $str= "<h1>Welcome</h1>$motto<br/>"; 
    echo $str.'<br />';  //result: welcome
    eval("\$str = \"$motto\";");
    echo $str;

Upvotes: 0

Related Questions