include & require
Split your code into reusable files — headers, footers, config.
What you will learn
- Reuse code with include and require
- Build a shared header/footer
Reuse files
include and require pull another PHP file into the current one — perfect for a shared header, footer or config used on every page. Instead of copying the same menu onto twenty pages, you write it once in header.php and pull it in everywhere. Fix it in one place and every page updates.
<?php include "header.php"; ?>
<h1>Welcome to my page</h1>
<?php include "footer.php"; ?>When PHP reaches include "header.php" it pauses, drops the entire contents of header.php in at that spot (as if you had typed it there), then carries on. So this page ends up as: everything in the header, then your <h1>, then everything in the footer — all stitched into one finished page.
Note: Output (in the browser): (the full header markup) Welcome to my page (the full footer markup) The visitor sees one seamless page. They cannot tell it came from three files — the joining happened on the server before the HTML was sent.
Note: require stops the script if the file is missing (use for essential files like config); include only warns and continues. Use require for anything the page cannot work without.
Q. Which stops the script if the included file is missing?
✍️ Practice
- Create a header.php and footer.php and include them on a page.
- Make a config.php with site settings and require it.
🏠 Homework
- Build a 3-page site that shares one header and footer via include.