Asked  9 Months ago    Answers:  5   Viewed   56 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

82

You can use eval() for this

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


ob_start();
eval("?>$test");
$result = ob_get_clean();
Wednesday, March 31, 2021
 
Neysor
answered 9 Months ago
92

Example code:

import subprocess

# if the script don't need output.
subprocess.call("php /path/to/your/script.php")

# if you want output
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
Wednesday, March 31, 2021
 
waylaidwanderer
answered 9 Months ago
94

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.

Saturday, May 29, 2021
 
CAMason
answered 7 Months ago
32

Needless to say you should find another solution ASAP. In the meantime you can eval the code like this:

$str = '<h1>Welcome</h1><?php echo $motto?><br/>'; // Your DB content

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

Demo: http://codepad.org/ao2PPHN7

I can't stress that enough: eval is dangerous, and application code shouldn't be in the database. Try a template parser like Smarty, Dwoo, or my favorite: Twig.

Thursday, June 3, 2021
 
rasmusx
answered 7 Months ago
99

Well, in this case you can just check whether there is a "bad word" in the user input string, and if it returns true, echo "You are a potty mouth."

You would want to use strpos()

e.g.

if( strpos($_POST['user_input'],'dog')!==FALSE ) {
    echo('You are a potty mouth');
}

If you have an array of "bad words" you'll want to loop through them to check any occur within user input.

Saturday, August 21, 2021
 
Comandeer
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share