6

I am using php eval() function, below are my statements:

$uid = 8;
$str = 'SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid';
eval("\$str = \"$str\"");
die("$str");
//$query = $_SGLOBAL['db']->query($str);
//$result = $_SGLOBAL['db']->fetch_array($query);

The output is: SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid That's to say the varibale $uid did not passed. How to pass a variable into the evaluated string. Thanks.

3
  • 2
    WTF? why do you need an eval at all? Just put double quotes in the assignment statment and forget about eval. Commented May 26, 2011 at 7:46
  • maybe it is just a simple example bro Commented Jan 19, 2018 at 6:37
  • 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. Commented Jun 2, 2021 at 7:22

5 Answers 5

4

According to php manual: http://php.net/manual/en/function.eval.php

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.

So, if the variable you need is defined in the scope where you calleval(), everything should work as expected.

Sign up to request clarification or add additional context in comments.

Comments

3

you can't insert varuiable into single-quotet strings directly. try this:

$str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; // double-quotet

or this:

$str = 'SELECT COUNT(*) FROM uchome_blog WHERE uid='.$uid; // string-concatenation

Comments

2

You are missing a semicolon. Try this:

eval("\$str = \"$str\";");

Comments

1

Variable substitution only works in double quoted strings.

Try this:

$uid = 8;
$str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; # variable gets substituted here
eval("\$str = \"$str\"");
die("$str");

I think variable substitution is something that happens at parse time - it is not done recursively, so in your eval, the contents of $str is pasted into the string, but that isn't done a second time for the contents of $uid inside $str.

Comments

1

You can use this too, but it makes no sense and it's the wrong logic for using eval

Example 1:

<?php
  $uid = 8;
  $OUTPUT = '<?php $str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; ?>';

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

Example 2:

<?php
  $uid = 8;
  $str = '<?php $str = "SELECT COUNT(*) FROM uchome_blog WHERE uid=$uid"; ?>';

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.