What is the best practice for including PHP files?

15,564

EDIT 2016

Well, 5 years since I replied this. I am still alive. A lot has changed.

Now I use autoloaders to include my files. Here is official info for autoloaders with examples.

Basically, the idea is to have a proper folder structure (PSR-4 standards for instance) and having a class within each file. This way you can use autoloaders and PHP will load your files automatically.

OLD ANSWER

Usually, I have a config file like this:

define(root, $_SERVER['DOCUMENT_ROOT']);
.... // other variables that are used a lot

include (root . '/class/database.php'); 
.... // other includes that are mostly called from each file, like a db class, or user class, functions etc etc...

if (defined('development'))
{
    // turn error reporting on
}
else 
{
    // turn it off
} 

etc etc... You got the point of config.

And I include the config.php on each file. I forgot how to do it right now, but apache can do the automatic include for you. Therefore, you can say to apache to include your config file by default.

Then, I have controller classes, which call the views. There in each function I call the view.

someController.php

function index() { include root . '/views/view_index.php'; }

finally, from the view, if I need to include the header and footer view I do it like this:

view_index.php

<?include root . '/view/shared/header.php';?>
<div class="bla bla bla">bla bla bla</div>
<?include root . '/view/shared/footer.php';?>

I always use include in this structure rather than include_once since the latter requires extra check. I mean, since I am pretty sure that I include files only once, I don't need to use include_once. This way, you also know which include is where. For instance, you know that crucial files like db.php, or functions.php are located in config.php. Or you know that include views are located in controllers. That's pretty useful for me, I hope that helps you, too.

Share:
15,564
SupaOden
Author by

SupaOden

Updated on June 09, 2022

Comments

  • SupaOden
    SupaOden almost 2 years

    What is the best practice for including PHP files?

    Is it best to include a include.php file that includes all of the project PHP files? Or to include it in those files that need them

    Right now, my project has several include files in my index.php file. Does including all of my php files in the index.php make it less efficient?

    Lastly, Where should one include the session check PHP file? in all of the PHP files?

  • ethmz
    ethmz over 8 years
    if(file_exists(require_once('classes/'.$class.'.php'))) in the first code block should be if(file_exists('classes/'.$class.'.php'))