Search code examples
phpeval

Please explain what this does: eval("\$str = \"$str\";")


This snippet of code is from the php.net manual on eval:

<?php

$string = 'cup';
$name = 'coffee';

$str = 'This is a $string with my $name in it.';
echo $str. "<br>";

eval("\$str = \"$str\";"); 
echo $str. "<br>";

?>

I somehow cannot comprehend what this line of code does: eval("\$str = \"$str\";").

I am guessing the net effect is something like:$str = "$str"; But when I use this in place of the eval code, I don't get the same effect. Can somebody walk me through this line of code. I am aware about the vulnerabilities that the function brings with it. But my point of interest is only limited to understanding that particular line of code.

I think I have my answer now -

eval("\$str = \"$str\";") and $str = "$str"; aren't the same thing. In the second case, $str is evaluated to This is a $string with my $name in it. and in the first case, the same string, since it is still inside the eval construct is further evaluated and results in This is a cup with my coffee in it.


Solution

  • eval() will execute the string it gets as if it were PHP code.

    $string = 'cup';
    $name = 'coffee';
    

    That's pretty much self-explanatory. Two values are stored in two variables, $string and $name.

    $str = 'This is a $string with my $name in it.';
    echo $str. "<br>";
    

    This will output:

    This is a $string with my $name in it.

    Notice that the variable isn't expanded. Variables aren't interpolated when they're used inside single-quotes -- so the result is as expected. This is documented here.

    eval("\$str = \"$str\";"); 
    echo $str. "<br>";
    

    This is probably what confuses you. Let's inspect it in detail. Inside the eval() statement, you have the following:

    "\$str = \"$str\";"
    
    • \$str - the variable is escaped with \ to avoid it from being interpreted as a string. If you remove the backslash from the beginning, PHP will throw a Parse error.
    • \"$str\"; -- the actual value of the variable is used here, and the backslashes are used to escape the double-quotes.

    When run, the PHP code to be executed would look like this:

    $str = "This is a $string with my $name in it.";
    

    In the end, you're just echoing the variable as normal, and it would just output:

    This is a cup with my coffee in it.
    

    The eval() function, like anything else could be very dangerous if incorrectly used. The manual warns you:

    The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.