Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Include or require

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.

Leave a reply