How to run php code from file_get_contents or file in a function

I am designing my own MVC pattern to ease the process of creating homepages. My templating system needs my controller class to output my views. This means I have to output the file through a php function. I have been searching for some a while now and can’t seem to find a solution.

How can I, through a PHP function, run a string representing some source code (“< ?”, “< ?php”, “? >” and so on) as php? Eval would not take my < ? signs (and I read that function is crap for some reason).

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You could execute the php code and collect the output like this:

ob_start();
include "template.phtml";
$out1 = ob_get_clean();

http://www.php.net/manual/de/function.ob-get-contents.php

Solution 2

Just include()ing the file instead should be fine. I’ve not dug that deeply into the source code but I’m fairly sure that’s how Zend Framework implements templates.

Solution 3

Replacing “echo file_get_contents()” with “include()” as GordonM suggested worked exactly as needed. can’t upvote yet since I’m too new but for my needs this is the direct answer to the headlined question.

Solution 4

$code = '<?php
function GetBetween($content, $start, $end) {
  $r = explode($start, $content);
  if (isset($r[1])){
    $r = explode($end, $r[1]);
    return $r[0];
  }
  return '';
}';

function _readphp_eval($code) {
  ob_start();
  print eval('?>'. $code);
  $output = ob_get_contents();
  ob_end_clean();
  return $output;
}

print _readphp_eval($code);

Solution 5

Well, eval is not crap per se, it’s just easy to create a security hole with that if you’re not careful about what you allow inside that eval (that, and maybe the fact that it can be bad for readability of the code).

As for the <? signs, that’s because eval expects php code, so if you wan’t to mix php with plain output, include just the closing ?> tag.

In general however, you can implement templates in better fashion, try to look into output buffering.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply