bladerunner1992
bladerunner1992

Reputation: 65

Is there a way to parse PHP from a file that has been loaded by PHP code?

I am loading HTML/PHP code from an external textfile with

$f = fopen($filename, "r");
while ($line = fgets($f, 4096)) 
{
  print $line;
}

Is there a way to have the server parse the PHP code that is in this file? I am currently only using a simple <?php echo("test"); ?> in the external file (held in $filename) to test if it works. I tried using ob_start() and ob_end_flush() in the main file, but to no avail. I am open to other solutions, but if possible, I'd like to maintain the separation of the files and use only PHP to ease future upgrades to the website.

Upvotes: 2

Views: 137

Answers (3)

Mike Mackintosh
Mike Mackintosh

Reputation: 14237

The following will do what you need.

If you are using it in a template type of scenario, ie, want to display data to a PHP file and echo the results use ob_start and get_clean to catch the output and store the results in a variabe:

ob_start();
eval('?>'.file_get_contents($file).'<?');
$result = ob_get_clean();

echo $result;

Otherwise, a simple:

eval('?>'.file_get_contents($file).'<?');

Will work.

Note: eval() should always be used sparingly and if possible, not at all for security and performance concerns.

Upvotes: 0

ksg91
ksg91

Reputation: 1299

You can use file_get_contents($link) to get the output of the file.

Check PHP Manual for file_get_contents()

Upvotes: 0

Nanne
Nanne

Reputation: 64399

It looks like you are looking for this: http://php.net/manual/en/function.eval.php

But please take the warning to heart:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

If anything, try to find a different sollution maybe?

Upvotes: 4

Related Questions