PHP Includes are a useful way to minimize duplicated code, and to improve your scripts overall maintainability.
There are a number of different ways to include files in your PHP scripts. There's Include, include_once, and require. Each have its own use, which will be explained in this tutorial. It will be up to you to chose which one you want to use.
Include and Include_once
Include will attempt to include whatever file specified, regardless if it exist or not. If the file wasn't found, the script will continue running anyway.
<?php include "whatever.php"; // Includes whatever.php ?>
The include_once statement will only include the file, if it hasn't been included earlier.
<?php include_once "whatever.php"; // Includes whatever.php include_once "whatever.php"; // Won't do anything, since the file was already included. ?>
If a file wasn't found, a warning is created. You will only be able to see this warning if you have enabled error reporting for your script.Warning: include(settings.php): failed to open stream: No such file or directory in path on line 50 Warning: include(): Failed opening 'settings.php' for inclusion (include_path='.;path') in path on line 50
Require indicates that the file is required, and that the script should stop executing if the file was not found.
<?php require "whatever.php"; // Includes whatever.php // The rest of the script, will only be finished if the above require succeeds ?>
A warning will be issued, depending on your error settings. If the warning does not show up in the browser, you can usually find it in the server log files.