PHP: How to include code from another file

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

In PHP, including code from another file is a common practice that helps in organizing code into reusable pieces. This not only makes code management simpler but also assists in creating a more maintainable codebase. In this tutorial, you’ll learn various ways to include PHP code from other files using include(), include_once(), require(), and require_once() statements.

Basic Usage of include()

The include() statement is used to take all the text/code/markup that exists in the specified file and copy it into the file that uses the include statement. This is particularly useful for including files like headers, footers, or elements shared across multiple pages.

<!-- header.php -->
<header>
  <h1>Welcome to My Website</h1>
</header>
<!-- end of header.php -->

<!-- index.php -->
<?php
include 'header.php';
?>
<main>
  <!-- Main content of your website -->
</main>

include_once()

The include_once() function is similar to include(), but it will only include the file once. If you try to include the same file again, it will not be included and will not cause an error. This is useful when the included file contains functions or classes and including it again might result in a fatal error.

<!-- functions.php -->
<?php
function foo() {
  echo 'Hello, I am a function.';
}
?>

<!-- another-page.php -->
<?php
include_once 'functions.php';
foo(); // Output: Hello, I am a function.
include_once 'functions.php'; // This will not include the file again.
?>

Understanding require()

The require() function is identical to include(), except upon failure, it will produce a fatal error and stop the script. Use require when the file is essential to the application.

<!-- config.php -->
<?php
// Database configuration
$host = 'localhost';
$username = 'root';
$password = 'root';
?>

<!-- index.php -->
<?php
require 'config.php';
// If config.php is not found, a fatal error will be thrown.
?>

require_once()

Similar to include_once(), require_once() will check if the file has already been included, and if so, it will not include it again. It throws a fatal error if the file cannot be included, and is best used for files that are essential to the script’s operation.

<!-- init.php -->
<?php
require_once 'config.php';
require_once 'functions.php';
// Use this file to include essential components ...
?>

Advanced Inclusion Techniques

For developers who require more control, PHP includes functions like file_exists() and is_readable() that can be used to check a file’s existence and permissions before attempting to include it.

<!-- index.php -->
<?php
$file = 'config.php';
if (file_exists($file) && is_readable($file)) {
    require $file;
} else {
    die('The required file is not available.');
}
?>

Autoloading Classes

In an object-oriented programming context, PHP provides a spl_autoload_register function which can automatically load classes by including the class file the first time a class is used.

<!-- autoload.php -->
<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});
?>

<!-- MyClass.php -->
<!-- Assuming the class name is MyClass and it's defined in MyClass.php -->

<!-- index.php -->
<?php
include 'autoload.php';
$myClass = new MyClass(); // The MyClass.php file is automatically included.
?>

Handling Paths

Learning how to manage file paths is crucial when including files. You can use __DIR__ and dirname(__FILE__) to ensure that you are including files with the correct directory path.

<!-- subfolder/index.php -->
<?php
require __DIR__.'/../config.php'; // Includes the file from the parent directory.
?>

Using these approaches wisely allows you to build scalable and well-organized PHP applications!

Summary

In this tutorial, you’ve learned the common methods for including one PHP file from another. By strategically organizing your code into separate files and including them when needed, you can make your code more readable, maintainable, and scalable. Whether you use include(), require(), their ‘once’ counterparts, or an autoloader, remember that choosing the right method based on your application needs is key to clean and efficient coding.