BananaMan
BananaMan

Reputation: 168

PHP code from a file does not execute

I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:

function parsecode($codetype) {
    $source = file_get_contents("file.php"); 
    $language = $codetype; 
    $geshi = new GeSHi($source, $language); 
    echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>"; 
    echo $geshi->parse_code();
}

This works perfectly fine!

Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:

$find = array( 
  "/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
  '<?php parsecode("$1"); ?>'
);

Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.

What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.

Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.

My question: Why does the function not execute & parse the code like it should?

Thanks ahead!

Upvotes: 0

Views: 97

Answers (1)

Ruby
Ruby

Reputation: 529

There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().

http://www.php.net/manual/en/function.eval.php

This let's you dynamically make code and execute it

Please remember this quote though: "If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"

eval() is known for security vulnerabilities and being exploited. Highly not recommended. However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.

You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...

Upvotes: 1

Related Questions