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
requirefor files your script can't work without. - Use
require_oncefor files that define functions or classes, so they're never declared twice. - Use
includefor 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.
<?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?
includerequireimportuse
Show answer
Answer: require