2

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.

8
  • 8
    what's wrong with include or require ? Commented Jun 18, 2012 at 14:18
  • Yes you can: eval($line); Commented Jun 18, 2012 at 14:18
  • define "external" - from another URL, or from the file system? Commented Jun 18, 2012 at 14:22
  • @RemcoOverdijk Rasmus Lerdorf, the creator of PHP once said "If eval() is the answer, you’re almost certainly asking the wrong question." This applies nicely in this situation. Commented Jun 18, 2012 at 14:28
  • 1
    @bladerunner1992 sounds like a perfect case for include, then! Commented Jun 18, 2012 at 15:36

3 Answers 3

4

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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

Check PHP Manual for file_get_contents()

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.