webnoon
webnoon

Reputation: 1005

PHP - eval() problem

I have two files like below

SomeClass.php

class SomeClass {
  public function display() {
    $content = file_get_contents("helloworld.php");
    eval($content);
  }

  public function helloWorld() {
    echo "hello World!";
  }

}

helloworld.php

<?php
  $this->helloWorld() ;
?>
<p>It's html expression</p>

As you can see, I tried to execute helloworld.php in the display function. Of course, It occur an error because the html tag is placed in the display function.

Is there any good way to execute helloworld.php text in the display function preserving helloworld.php code?

Upvotes: 1

Views: 746

Answers (4)

ohmusama
ohmusama

Reputation: 4215

There is no way to do this, unless you want to do string concatination.

I tested this with a few minor changes to the helloworld.php file as such it works:

$this->helloWorld() ;
?><p>It's html expression</p>

This shows that the text is run raw as if it were hard included.

Now if you DONT or CANT change the open <?php tag, you can go one of two ways.

The easy way (String Concatenation):

public function display() {
    $content = file_get_contents("helloworld.php");
    eval('?>' . $content); //append a php close tag, so the file looks like "?><?php"
}

The harder way (String Replace):

public function display() {
    $content = file_get_contents("helloworld.php");

    //safely check the beginning of the file, if its an open php tag, remove it.
    if('<?php' == substr($content, 0, 5)) {
        $content = substr($content, 5);
    }
    eval($content);
}

Upvotes: 1

AndrewR
AndrewR

Reputation: 6748

You can capture it with output buffering.

ob_start();
include "helloworld.php";
$content = ob_get_contents();
ob_end_clean();

Upvotes: 1

Gaurav
Gaurav

Reputation: 28755

you can use include or require for this purpose.

Upvotes: 0

Charles
Charles

Reputation: 51411

If you're trying to execute a specific file in the context of the current code, why not use include or require?

Remember, if eval is the answer, the question is wrong.

If you really want to use eval here,

eval('?>' . $content);

should work. Yes, you can close and reopen the PHP tag inside. This is how certain template engines work.

Upvotes: 2

Related Questions