Include php code within echo from a random text

2019-08-01 17:04发布

问题:

I want to display a php code at random and so for I have

<?php

// load the file that contain thecode
$adfile = "code.txt";
$ads = array();

// one line per code
$fh = fopen($adfile, "r");
while(!feof($fh)) {

  $line = fgets($fh, 10240);
  $line = trim($line);
  if($line != "") {
    $ads[] = $line;
  }
}

// randomly pick an code
$num = count($ads);
$idx = rand(0, $num-1);

echo $ads[$idx];
?>

The code.txt has lines like

<?php print insert_proplayer( array( "width" => "600", "height" => "400" ), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?>

Proplayer is a wordpress plugin that displays a video. The codes in code.txt work well, but not when I use the pick line from code.txt. Instead of the full php line I get:

"width" => "600", "height" => "400" ), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?>

How can I make the echo show the php code, rather than a txt version of the php code?

回答1:

Try using htmlentities() to escape the php code. Something like:

$string = '<?php print insert_proplayer( array( "width" => "600", "height" => "400" ), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?>';
echo htmlentities($string);


回答2:

Use eval: http://php.net/eval.

Edit:

Or better yet, use includes. This could be if-else statements, a switch statement, an array, or anything that can select from among choices. Example code.php:

<?php
    if ($i == 1)  // use better variable name
        print 'blah blah blah';
    else if ($i == 2)
        print 'blah blah blah';
    else if ($i == 3)
        print 'blah blah blah';
    // ...
    else if ($i == $max)
        print 'blah blah blah 4';
?>

Calling page:

<?php
    $max = 5;  // set max to however many statements there are
    $i = rand(1, $max);
    include('code.php');
?>


标签: php random echo