PHP Include and Require Statements

PHP Include and Require Statements

PHP Include and Require Statements, both are used to include a specific PHP code written in one file to another file.

Generally a path name is written with the file name after include or require keywords. if the directory is same then there is no need to write the path name. Including files using include or require statement is very useful, instead of writing same code in more than one file we can simply write it in one specific file then include that file using include or require statement everywhere we want.

You can include both HTML or PHP type files using include or require statement.

Difference between Include and Require Statement

The include and require statement, both work in the same way except for the instance when both fail to find the specified file.

Require Statement

The require statement will produce a fatal error (E_COMPILE_ERROR), means the further execution of the code will stop if the required file is not found.

Include Statement

The include statement will produce a warning (E_WARNING) but the further execution of PHP script won't stop.

Which one to use: Include Statement or Require Statement

The answer to this question is pretty simple. If you are including an important file that is necessary for the further execution of the script then the require statement should be used.

The reason of this is that the require statement stops the execution of script, if the required file is not found and you will know that file is not found.

But, if you want that your script execute properly and gives the output to user even if the required file is not found then you should use include statement.

Syntax of Include Statement

The syntax of Include Statement is shown below.

include 'filename';

Syntax of Require Statement

The syntax of Require Statement is shown below.

require 'filename';

Why we use Include or Require Statements

In practice while making websites, we commonly use include or require statement to include header, footer or menu of website in all the pages of website.

In this way if we want to change, let's say the footer of our website, we will only make changes in footer file and it will be applied to all the pages that are including this footer file.

That is why both include and require statements are widely used and are extremely helpful.