Understanding Include and Require in PHP: Connecting Files Correctly

In PHP, you can include some files in others. This allows you to structure your project, making the code more logical and manageable. This practice helps to divide responsibilities between program components — for example, moving repetitive functions or parts of markup into separate files.

One convenient way to manage connections is to use the magic constant DIR, which returns the path to the folder where the current script is located. This is especially useful when you are working with relative connection paths and want to avoid errors.

Architecture example

Suppose you want to check whether a number is even. The function that performs the check can be moved to a separate file, say functions.php. Then, in the main file, for example index.php, you include this file using include or require, and call the desired function within the HTML content.

The difference between include and require

  • include connects the file, and if it is not found, PHP will generate a warning, but the script will continue to run.
  • require, on the other hand, causes a fatal error if the file is missing and terminates the script.

Therefore, require is used for files without which execution is impossible — for example, for configuration or basic functions. Include is suitable for optional elements, such as advertising blocks.

Re-loading: include_once and require_once

When you need a file to be loaded only once (for example, with functions or settings), use include_once or require_once. Even if you try to load the file multiple times, PHP will ignore the repeated calls.

Example with a website template

Let’s say you have a website with a common structure — a header, sidebar, main content, and footer. All these parts can be moved to separate files: header.php, sidebar.php, content.php, footer.php. Then, in the main file, you simply include these components sequentially. This makes the code clear and easy to maintain.

You can also pass data to the included parts. For example, you set the $content variable before including content.php, and then simply output its value in it. This allows you to generate page content dynamically, without duplicating code.

Connecting HTML via PHP

Files containing HTML can be connected in the same way. This is especially useful when you want to reuse the same pieces of the interface on different pages without copying them manually.

In the end, the file connection system in PHP is a tool not only for reducing code, but also for building a clear project architecture. Use require for mandatory components, include for auxiliary ones, and their versions with _once to prevent repeated connections.