Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Equivalent of include using eval

Tags:

include

php

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).

like image 712
Jasper Avatar asked Jul 26 '09 13:07

Jasper


People also ask

What is eval function PHP?

Definition and Usage. The eval() function evaluates a string as PHP code. The string must be valid PHP code and must end with semicolon. Note: A return statement will terminate the evaluation of the string immediately. Tip: This function can be useful for storing PHP code in a database.

How do you use eval?

The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function. For example, Eval("Chr$(65)") returns "A".

What is the purpose of using the eval function in conjunction with the input function?

If you call Python's eval() using a compiled-code-based input, then the function performs the evaluation step and immediately returns the result. This can be handy when you need to evaluate the same expression multiple times.


2 Answers

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;');
like image 167
Jasper Avatar answered Sep 29 '22 08:09

Jasper


AFAIK you can't take advantage of php accelerators if you use eval().

like image 24
niteria Avatar answered Sep 29 '22 09:09

niteria