PHP Include and Require

PHP Include and Require

include and require let you split code across files and reuse it — perfect for config files, layouts, and shared functions.

1 - The Four Statements

  • include — includes file; shows warning if missing, script continues
  • require — includes file; fatal error if missing, script stops
  • include_once — includes once even if called multiple times
  • require_once — requires once even if called multiple times

2 - Shared Config

// config.php
define("DB_HOST", "localhost");
define("DB_NAME", "myapp");

// index.php
require_once "config.php";
echo DB_HOST; // localhost

3 - Reusable Layout

// header.php
?><header><h1>My Site</h1></header><?php

// footer.php
?><footer>© 2024</footer><?php

// page.php
require "header.php";
echo "<main>Page content</main>";
require "footer.php";

4 - Including with Variables

$title = "About Us";
$body  = "We build great software.";
include "template.php"; // $title and $body are available inside

Note: With Composer autoloading, you rarely need include/require for classes. Use them for config files, bootstrap scripts, and view templates.

-Tip-