pokrak94
pokrak94

Reputation: 202

eval() function in PHP, how to make this work properly on the website?

I have a problem with eval() function. Please do not comment something like "Don't use eval" or anything of this kind of thing, as this is not helpful. I have a very good reason to use eval().

Basically I am getting a value from a text field in html on my web page as input code to be executed, like so:

$code = $_POST['code'];

Then, am passing that value to eval function in the html body, like so:

eval($code);

the results are displayed like this:

<h1>test</h1> 

the above is displayed string. I want this to execute the html part of it is well. Funny thing is if I try this in a different file like this:

<?php
$code = "echo '<h1><b>TEST</b></h1>';";
eval($code);
?>

I get the desired result, which is a proper processed html element h1 with "TEST" in it.

Any ideas? Thanks in advance

Upvotes: 0

Views: 579

Answers (1)

Barmar
Barmar

Reputation: 780673

$_POST['code'] apparently contains HTML entity codes, e.g.

"echo '&lt;h1&gt;test&lt;/h1&gt';"

You need to decode it before calling eval.

eval(html_entity_decode($_POST['code']));

Upvotes: 3

Related Questions