Include php code within echo from a random text

只愿长相守 提交于 2019-12-24 10:48:34

问题


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');
?>


来源:https://stackoverflow.com/questions/5035740/include-php-code-within-echo-from-a-random-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!