Search code examples
phpincludeeval

PHP: Equivalent of include using eval


If the code is the same, there appears to be a difference between:

include 'external.php';

and

eval('?>' . file_get_contents('external.php') . '<?php');

What is the difference? Does anybody know?


I know the two are different because the include works fine and the eval gives an error. When I originally asked the question, I wasn't sure whether it gave an error on all code or just on mine (and because the code was evaled, it was very hard to find out what the error meant). However, after having researched the answer, it turns out that whether or not you get the error does not depend on the code in the external.php, but does depend on your php settings (short_open_tag to be precise).


Solution

  • After some more research I found out what was wrong myself. The problem is in the fact that <?php is a "short opening tag" and so will only work if short_open_tag is set to 1 (in php.ini or something to the same effect). The correct full tag is <?php, which has a space after the second p.

    As such the proper equivalent of the include is:

    eval('?>' . file_get_contents('external.php') . '<?php ');
    

    Alternatively, you can leave the opening tag out all together (as noted in the comments below):

    eval('?>' . file_get_contents('external.php'));
    

    My original solution was to add a semicolon, which also works, but looks a lot less clean if you ask me:

    eval('?>' . file_get_contents('external.php') . '<?php;');