Include or require

In PHP there are two ways to include or pull in other files into a document. These are the “include” and “require” commands. This is an efficient way to pull in commonly used functions whenever you need them and not just paste them in your files over and over again. For example, you would probably need to use certain configuration or database details frequently. You would store these details in separate files, and include or require them whenever you need them.

The “include” and “require” statements

These two statements do exactly the same. They fetch a specific file and load all its content.

Basic usage:

<?php

   include "config.php";

   // rest of your code here

?>

or

<?php

   require "config.php";

   // rest of your code here

?>

The only difference between the two is error handling.

If there is a problem, “include” will give you a warning, but your script will continue to run. However, “require” will produce a fatal error and will stop the execution of the script.

The “include_once” and “require_once” statements

It’s possible that we inadvertently include a file multiple times. For example, we include a file that already has another included in it, which we had already included in our document. This could produce error messages.

To avoid this problem, we can use the “include_once” or “require_once” statements.

Basic usage:

<?php

   include_once "config.php";

   // rest of your code here

?>

or

<?php

   require_once "config.php";

   // rest of your code here

?>

If we use these, the inclusion of the same file will be ignored.

In general it’s best to stick with “include_once” or “require_once”, but if you don’t want to reveal potential details about your system, it’s best to use “require_once” only.

ChristianKovats
ChristianKovats

Christian Kovats is a London-based web designer who loves crafting innovative and user-friendly interfaces. His passion for design is only rivaled by his love for nature and hiking, often drawing inspiration from his treks through the diverse landscapes of the UK. Outside of work, Christian enjoys spending quality time with his wife and 4-year-old son. A seasoned lucid dreamer, he also spends time exploring the intricate world of dream interpretation, reflecting his ever-curious and creative mind.

ChristianKovats

Leave a reply

You must be logged in to post a comment.