I have been working with several new clients lately, mostly helping them update their websites with new content. Most of these websites were created by other companies or individuals and I am always amazed at how people create websites. One of the things that I am always amazed at is why people don’t take advantage of using includes to make managing a website easier. Individual web pages in a website are made up of many common elements: headers, menus, footers. There is no reason to duplicate these items across the website when a single file can be included on all the pages to make management of the website easier. Most web servers have PHP installed on them, so may use of it to make managing your website easier.
The PHP include() and include_once() functions will allow you to include those common elements in all pages. If you have a common menu you can use a simple include such as:
You might have to change your path. For example I like to keep all the include files in a separate folder so my includes will often look something like this:
To edit the menu and make the change across the entire website all I need to do is edit the one file menu.php. This can save you a considerable amount of time, especially if you have hundreds or thousands of web pages to edit.
The PHP functions that are most often used to include files are (from the PHP Documentation):
The include() statement includes and evaluates the specified file.
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.
require() and include() are identical in every way except how they handle failure. They both produce a Warning, but require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page.
The require_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the require() statement, with the only difference being that if the code from a file has already been included, it will not be included again.
When to use include() or require() can be an entire other post, but generally I use require() when the website needs that file to run. Site wide configuration files for example. If the file cannot be included it will stop the site from running. I use include() when it is less critical, so menus, headers, footers. The website might not look great if the menu does not get included but it will still display the information to people.