1. Home
  2. Docs
  3. Web Technology II
  4. Introduction
  5. Including and Requiring Files

Including and Requiring Files

In PHP, the include and require statements allow you to incorporate external files into your scripts, making it easy to organize and reuse code.

• Both include and require are used for the same purpose, but they differ slightly in how they handle errors.

The include statement is used to insert the contents of one PHP file into another PHP file.

  • If the specified file cannot be found or opened, PHP will emit a warning, but the script will continue executing.

• include is generally used when the file is not essential to the script’s execution. For instance, adding optional files like footers or headers where it’s acceptable if they aren’t found.

// Including an external file
include 'header.php';
echo "Welcome to the homepage!";

If header.php doesn’t exist, PHP will display a warning but will still execute the remaining code.

The require statement is similar to include, but it’s more strict.

  • If the specified file cannot be found, PHP will throw a fatal error, and the script will stop executing.

• require is commonly used when the file is essential for the application, such as files containing key functions, configurations, or database connections.

// Requiring an external file
require 'config.php';
echo "Configuration loaded!";

If config.php is missing, PHP will stop executing and show a fatal error.

Differences Between include and require

Both include_once and require_once are used to include files in a PHP script, ensuring that each file is included only once, even if the statement is called multiple times in the code. This helps prevent errors and conflicts that could arise from multiple inclusions of the same file.

  1. include_once

include_once includes and evaluates the specified file during the script’s execution. It checks if the file has already been included and, if so, does not include it again. If the file is missing or an error occurs, it issues a warning, but the script continues execution.

// Ensures 'functions.php' is included only once
include_once 'functions.php';
require_once 'config.php';
    1. require_once

    require_once includes and evaluates the specified file only once. Like include_once, it checks if the file has already been included, but it differs in error handling. If the file is missing or an error occurs, require_once issues a fatal error, and the script stops execution.

      // Ensures 'functions.php' is included only once
      include_once 'functions.php';
      require_once 'config.php';

      How can we help?

      Leave a Reply

      Your email address will not be published. Required fields are marked *