PHP Tutorial · PHP for the Web · Lesson 22 of 38

PHP Include and Require

Split code into files with include, require and require_once.

Reusing files

Put shared code — a header, configuration, functions — in its own file and pull it in:

<?php
require __DIR__ . "/config.php";        // fatal error if missing
require_once __DIR__ . "/functions.php"; // only loaded once
include __DIR__ . "/partials/header.php"; // warning if missing, script continues
  • Use require for files your script can't work without.
  • Use require_once for files that define functions or classes, so they're never declared twice.
  • Use include for optional pieces like template partials.
  • Build paths from __DIR__ so they work no matter where the script is run from.

A file can return a value

A common pattern is a config file that returns an array:

<?php
// config.php
return [
    "db_host" => "localhost",
    "debug" => true,
];
<?php
$config = require __DIR__ . "/config.php";
echo $config["db_host"];

In modern projects, Composer's autoloader loads classes automatically, so you rarely write many require lines — see Composer.

Example 1Try it yourself
<?php
// Write a config file, then require it — just like a real project.
$file = sys_get_temp_dir() . "/config.php";
file_put_contents($file, '<?php return ["app" => "ReadyCamel", "debug" => true];');
$config = require $file;
echo $config["app"], " debug=", var_export($config["debug"], true), "\n";

Output

ReadyCamel debug=true

Test yourself

Which statement stops the script with a fatal error if the file is missing?

  1. include
  2. require
  3. import
  4. use
Show answer

Answer: require