Jump to content

The function eval() serves to print code stored in variables?


edecode

Recommended Posts

Hello guys,

 

I am studying about function eval() and I can't know how and why this functions is necessary! I wrote this code:

<?php
		$string = "beautiful";
		$time = "winter";

		$str = 'This is a $string $time morning!';
		echo $str. "<br>";

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

		$code1 = "echo 'Hello World!'; ";
		$code2 = "?>";
		 
		$code_php = '<?php $code1 $code2';
		echo $code_php;

		eval("\$code_php = \"$code_php\";");
		echo $code_php;
		
?>

On first echo the result should be this: "This is a beautiful winter morning!", that's right?

On second echo the result should be a code in php "This is a $string $time morning!"

On third echo the result should be this: "Hello World"

Lastly, the fourth echo the result should be a code in php: "<?php $code1 $code2"

 

Am I do this right?

Thanks

 

 

Link to comment
Share on other sites

eval() runs PHP code that's in a string. See documentation about it here: http://php.net/eval

 

The string should not have <?php tags in it, because eval() starts off inside the PHP block already and <?php would be a syntax error.

 

You should never use eval(), there's no good reason to and it opens the possibility of users running their own scripts on your server.

  1. The first echo would output "This is a $string $time morning!" because the string is wrapped in single-quotes which does not parse variables.
  2. The second one would show "This is a beautiful winter morning!" because the variables have been evaluated.
  3. The third one would literally print "<?php $code1 $code2" because the string is wrapped in single-quotes.
  4. The fourth one would literally print "<?php echo 'Hello World!'; ?>"

If you wanted eval to print "Hello World!" then you would have to do this:

$code = "echo 'Hello World!';"
eval($code);

Don't put <?php ?> tags in code that's suppose to be evaluated because it would throw a syntax error. If inside the eval() string you put contents in double quotes it will just consider it a string and not PHP code.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...