Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include semantics

I am trying to work out how to interpret PHP's include construct, e.g. whether it is textual inclusion, when it is evaluated etc. As usual, the documentation is rather informal and vague.

Based on experimentation, it seems to be syntactic sugar. Specifically, the construct

include 'Baz.php'

is an expression which can be replaced with

eval('?>' . file_get_contents('Baz.php',  FILE_USE_INCLUDE_PATH))

Is this correct? Is this substitution true in the general case, or just in my tests?

Edit: as bwoebi notes, this is not generally true since the evaluated code does not have the same __DIR__ and __FILE__ magic constants. If there were some way to set them, we could model that too.

Edit 2: this question is a duplicate of this one: Equivalent of include using eval. However, all the answers there appear to omit bwoebi's point about the file path context.

like image 782
jameshfisher Avatar asked Dec 05 '25 20:12

jameshfisher


1 Answers

Yes, that should be generally true.

The only differences are:

  • file context (it's now eval()'ed code, not code from that file)
  • relative paths: when you include files in other directories and they use theirselves relative paths, the file it points to might now not be found anymore
  • file_get_contents() is not affected by allow_url_include ini setting (though allow_url_fopen affect both)
like image 117
bwoebi Avatar answered Dec 08 '25 12:12

bwoebi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!