include and require functions in PHP

There are certain scenarios where we want the same PHP statements to be executed every time for most of the PHP files. One such scenario is for the database connection, where every time a PHP file with some SQL queries in it gets executed on the server, there needs to be present a database server connection code at the start of that PHP file, which else-wise would keep failing to execute the SQL queries on the database server without the needed connection available.

Such scenario can be handled by using two of the popular functions provided by PHP to include on PHP file into another, which are include() and require().

The sole purpose of both the methods are same i.e. they both include the text from the specified file into the file that uses the include function.

Let’s understand this with some of the examples.


So let’s assume we have a PHP file named abc.php with its content as:

There is another PHP file main.php that includes abc.php file as:

Executing main.php on the server, will display the following on the browser:

Now let’s change main.php a little to something like:

Note that we have now included abcd.php instead of abc.php, which doesn’t exist on the server. When executed, main.php will display a warning message and at the same time displays the following on the browser:

This means that even if there is an error in including any file, the PHP script still continues to execute, which in itself might prove to be a big security flaw in the long run. However, to the rescue, there is another predefined method require in PHP that does the same thing as include, with similar syntax, but if there is any error in the require statement, such as if the file is missing/misnamed, PHP script stops execution then and there.

That is the reason why PHP require is always preferred over include.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.