Search code examples
phpeval

How can I use single quotes with nested calls to eval()?


I am trying to use single quotes with nested calls to eval():

eval('eval(\'echo 'hi\';\');');

However, this triggers the following error:

syntax error, unexpected 'hi' (T_STRING)

How can I use single quotes and resolve this error?


Solution

  • You have an issue escaping single-quotes. You may use double quotes instead—"hi" instead of 'hi':

    eval('eval(\'echo "hi";\');');
    

    If you need to use single quotes, the backslashes that escape the single quotes will themselves need to be escaped, with a pair of additional backslashes (\\); i.e:

    eval('eval(\'echo \\\'hi\\\';\');');
    

    This yields:

    hi

    As you can imagine, this will get messy quickly as the level of nesting increases.

    It's worth noting that eval() is considered to be dangerous and you should only use it in very deliberate circumstances where you have thoroughly evaluated that there is no risk in using it, and there are no better ways to achieve what you are trying to do.

    As stated in the PHP documentation:

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

    It's worth searching Stack Overflow for some discussion on its usage.

    Hope this helps :)