Summary - File inclusion
Build a simple site skeleton with include, __DIR__ and partials.
Summary - File inclusion
In this group you saw the four statements for file inclusion in PHP: include continues with a warning, require raises a fatal error, include_once and require_once include a file only once. When you build paths with __DIR__, the script runs correctly from any directory.
With these tools you can combine partial files (header, footer, content) into consistent page layouts. On large sites every page shares the same skeleton; a change is made in a single partial. In the next section you will see require_once again for OOP and class autoloading.
Exercise Combine header, content and footer partials in a layout
Assign sys_get_temp_dir() to $dir. Create $dir . "/header.php", $dir . "/content.php" and $dir . "/footer.php" with file_put_contents; the contents are "<?php echo 'HEADER'; ?>", "<?php echo 'CONTENT'; ?>", "<?php echo 'FOOTER'; ?>" in order. Then write, in order, require $dir . "/header.php";, echo " ";, include $dir . "/content.php";, echo " ";, require $dir . "/footer.php";.
Show example solution
First set $dir = sys_get_temp_dir();. Write header.php, content.php and footer.php with file_put_contents. Then add require $dir . "/header.php";, echo " ";, include $dir . "/content.php";, echo " ";, require $dir . "/footer.php";.
Example solution:
<?php
// Create header, content and footer partials and combine in a layout
$dir = sys_get_temp_dir();
file_put_contents($dir . "/header.php", "<?php echo 'HEADER'; ?>");
file_put_contents($dir . "/content.php", "<?php echo 'CONTENT'; ?>");
file_put_contents($dir . "/footer.php", "<?php echo 'FOOTER'; ?>");
require $dir . "/header.php";
echo " ";
include $dir . "/content.php";
echo " ";
require $dir . "/footer.php";
Test yourself
-
Match statements to their features
- include
- Continues with warning
- require
- Stops with fatal error
- include_once
- Once, warns
- __DIR__
- Absolute directory path
-
Require the must-have file
require __DIR__ . '/____.php';Show answer
require __DIR__ . '/config.php'; -
Which statement stops the script when a file is missing?
- include
- include_once
- require
- echo
Show answer
require — Correct. require raises a fatal error and stops the script when the file is missing.