开发者

Include php code within echo from a random text

开发者 https://www.devze.com 2023-02-12 00:01 出处:网络
I want to display a php code at random and so for I have <?php // load the file that contain thecode

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=xnPCpC开发者_如何学PythonVepCg"); ?>

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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消