Viewed   84 times

What I want to do is pull html and PHP code out from a database and then execute it. So for example I may have:

<?php 
  $test = <<<END
    <p> <?php 
    echo time(); 
    ?> </p>
    END;
  echo $test;
?>

What I want is to get $test to print

<p> 12:00PM </p>                  //right

instead of printing:

<p> <?php echo time(); ?> </p>    //wrong

as occurs when I use the echo function.

Please do not tell me how to do the same thing with JavaScript or other work around. Instead stick to the question and remember the example is just an example to demonstrate my problem. The actual code is much more complicated.

I have looked at Javascript string variable that contains PHP code but none of the answers work.

Thanks,

Brett

 Answers

4

You can use eval() for this

$test = <<<END
<p> <?php 
echo time(); 
?> </p>
END;


ob_start();
eval("?>$test");
$result = ob_get_clean();
Monday, August 29, 2022
4

There is runkit, but you may find it simpler to just call the script over the command line (Use shell_exec), if you don't need any interaction between the master and child processes.

Monday, October 24, 2022
 
am_skp
 
4

Escape with a backslash, use "." for concatenation.

$row = array();
$row['ID'] = 1;

echo '<tr onclick="DoNav('list.php?id=' . $row['ID']. '');">';

Output

<tr onclick="DoNav('list.php?id=1');">

Also make sure to escape any content you're going to use in Javascript or HTML. For an ID, you might just cast as an integer:

echo '<tr onclick="DoNav('list.php?id=' . (int)$row['ID']. '');">';

Strings'll be more important to escape.

Tuesday, September 27, 2022
 
chandmk
 
4

You can use the ob_start() and ob_get_contents() functions in PHP.

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

Will output :

string(6) "Hello "
string(11) "Hello World"
Monday, December 5, 2022
4

Just a guess... replace the php brackets with HTML entities (&lt; and &gt;) so it will not be interpreted as PHP code (if you run the file containing the JS through PHP) nor as strange HTML code (the browser searches for brackets as html tags, remember...) by the browser.

Saturday, October 8, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :