Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to put a lot of PHP includes on a site?

Tags:

include

php

So far I have about 3 PHP includes on my site.

<?php include("includes/header.html"); ?>

Is there any reason why I shouldn't add a ton of these?

like image 445
omnix Avatar asked Nov 07 '10 04:11

omnix


3 Answers

Not really. They're used quite often and liberally—though more often than not, to include other PHP files. Those PHP files then often include other ones, so there's really no concern.

By the way, if you do use this technique to include other PHP files (e.g. library files with functions you're using), it's a good idea to use require_once (there's also include_once, as well as plain require); require will cause an error if its argument cannot be found, and won't continue trying to render the page. require_once (and include_once) will not include the same file more than once, even if you call require_once (or include_once) from different places.

like image 137
Asherah Avatar answered Sep 27 '22 23:09

Asherah


I suspect that you are doing something like this:

<?php
  include("session_and_headers.php");
  include("top_nav.html")
  include("right_sidebar.html");
?>

 ... actual content generation code ...

<?php
  include("footer.html");
  include("js_loader.php");
?>

There is nothing inherently wrong with that for simple static sites, or situations where users will have only several distinct views.

But, what happens if you want to use a slightly different side bar on only certain types of pages? Where do you put the logic to determine that so it is obvious to the next person who inherits your code?

If you get into those kinds of complexities, I recommend going with the MVC approach (even if you mostly use the view/controller aspects of it).

If you're doing a nn page site in PHP that just needs to share common elements, then there is no reason to avoid simply including the files as needed.

Don't look at this so much as is it bad for PHP, look at it more as is it hard to maintain?

like image 26
Tim Post Avatar answered Sep 27 '22 21:09

Tim Post


There's one advantage to writing object-oriented code and upgrading to PHP 5: you can avoid a "ton of includes" using class autoloading.

like image 22
bcosca Avatar answered Sep 27 '22 23:09

bcosca