CodeBlanks Logo Icon CodeBlanks

Including files with require

PHP course · Beginner · Lesson 107/116

Learn to include files with require and the difference (fatal error) from include.

The require statement

The require statement brings another PHP file into the calling script just like include; the included code runs as if it were written in the calling file.

The only difference is the error behavior: when the file is missing, include only warns, while require raises a fatal error and stops the script. This makes require the right choice for must-have files: database connections, configuration settings, function libraries. Without these files the script would run in a broken state, so failing early with require is safer.

When to choose which statement?

Which statement to pick depends on the importance of the file. Use require for must-haves and include for optionals.

Your database connection file (db.php), your configuration file (config.php) or your function library are must-haves; you use require for them. Without these files the script would either crash or create a security hole. Sidebars, ad slots or optional widgets are good fits for include; the page still works if they are missing. In practice, most teams default to require and reach for include only for truly optional pieces.

Exercise Create header.php and require it

Assign the path sys_get_temp_dir() . "/header.php" to $file. Write the file with file_put_contents($file, "<?php echo 'Site Title'; ?>"). Then require the file with require $file;.

Show example solution
First set $file = sys_get_temp_dir() . "/header.php";. Then write file_put_contents($file, "<?php echo 'Site Title'; ?>");. Finally add require $file;.
Example solution:
<?php
// Create header.php and require it
$file = sys_get_temp_dir() . "/header.php";
file_put_contents($file, "<?php echo 'Site Title'; ?>");
require $file;

Test yourself

  1. What is the main difference between include and require?

    • require raises a fatal error when the file is missing
    • include raises a fatal error when the file is missing
    • require only works with function files
    • include includes the file twice
    Show answer

    require raises a fatal error when the file is missing — Correct. require raises a fatal error and stops the script when the file is missing; include only warns.

  2. Require config.php

    require '____.php';
    Show answer
    require 'config.php';
  3. Match include and require behaviors

    include, file missing
    Warns, runs on
    require, file missing
    Error, stops
    File exists
    Both run the code
    Variable scope
    Shared

All lessons in Beginner