CodeBlanks Logo Icon CodeBlanks

Including files with include

PHP course · Beginner · Lesson 106/116

Learn to include another PHP file in a page with include.

The include statement

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

For example, include 'header.php'; reads header.php and runs its content at the call site. This way you can keep repeated headers, menus or helper functions in separate files and pull them in with include instead of rewriting them on every page. If the file is missing, PHP emits a warning but the script keeps running.

Missing file gives a warning

When an include call cannot find the file, PHP emits a warning but the script keeps running. This makes include suitable for optional files.

For example, a page sidebar may not always exist; with include 'sidebar.php'; you only get a warning if the file is missing, and the main page still works. For must-have files, require is safer because the script stops when the file is missing. It is also important not to ignore the warning: fix the file path instead of hiding the error.

Exercise Create greeting.php and include it

Assign the path sys_get_temp_dir() . "/greeting.php" to $file. Write the file with file_put_contents($file, "<?php echo 'Hello'; ?>"). Then include the file with include $file;.

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

Test yourself

  1. What does include 'menu.php'; do?

    • Only checks the file exists, does not run the code
    • Reads the file and runs its code at the call site
    • Prints the PHP code as HTML to the screen
    • Converts the file into a require statement
    Show answer

    Reads the file and runs its code at the call site — Correct. include reads the file and runs its code at the call site as PHP.

  2. Include header.php

    include '____.php';
    Show answer
    include 'header.php';
  3. Match the include behavior

    File missing
    Warns and continues
    File exists
    Runs its code
    Included variable
    Visible in caller scope
    File path
    Relative or absolute

All lessons in Beginner