Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If an include() is conditional, will PHP include the file even if the condition is not met?

Tags:

php

This has been on my mind for quite some time and I figured I should seek an answer from experts. I want to know if it is a poor programming technique to funnel all PHP requests through a single file. I have been working on a website and not sure if it will scale with growth because I am not 100% certain of how PHP handles the include() function.

To better explain how I have build my quasi framework here is a snippet of my root .htaccess file:

# > Standard Settings
RewriteEngine On

# Ignore all media requests
RewriteRule ^media/ - [L]

# Funnel all requests into model
RewriteRule ^(.*)$ _model.php [QSA]

So everything except content within the media directory is passed into this single script.

Inside _model.php I have all my input sanitisation, user authentication, session data gets pulled from the database, any global variables (commonly used variables like $longTime, $longIP etc...) are set. Requests are routed via interpreting the $_SERVER["REQUEST_URI"] variable.

Essentially I have a switch() statement which chooses which module to include(). What I don't understand is: when PHP executes, will it execute every single include() regardless of whether or not the case directive is true?

I am concerned that after time I will have a lot of these modules - and if PHP does at runtime include all the modules it will end up occupying too much processing power and RAM...

--

Edit:
I am really just asking if PHP will 'read' all those files that it potentially might have to include. I know that it shouldn't actually execute the code. If one of my include() is a 2GB file which takes a long time to process, will PHP always read over that file before executing?

-- Edit:
I have found another similar question (I did search a lot before posting this one) PHP behavior of include/require inside conditional

I think I can close this off.

like image 618
cstrat Avatar asked Nov 16 '25 21:11

cstrat


1 Answers

No, PHP will execute include in the moment the code fragment is reached.

This is quite important, because you can have php include file with code directly. E.g.

File1:

<?php echo "Foo"; ?>

File2:

<?php
  echo "Before";
  include("File1");
  echo "After";
?>

Sometimes your PHP processor won't even know at compiletime which file to include. Imagine something like include("File".mt_rand(1,10));. PHP won't know the filename to include up to the very moment it reaches the include statement.

like image 188
yankee Avatar answered Nov 19 '25 11:11

yankee