PHP file include() and require() function

PHP File Inclusion

PHP has two function which can used to include one PHP file into another PHP file before the server executes it.

  • The include() function
  • The require() function

For the designing purpose in web forms the same header, footer or menu displayed on all web pages of website. Programmer has to design same menu on multiple pages, if changes required in future it will very complicated to open all pages then make change on all pages.
for resolving this problem we use include and require function in php. Just design menu or header in one php page and display same menu on multiple pages using include function. if changes required on menu.php page, it will make effect on all other pages automatically.


The include() function

The include function copy all text of one PHP file into another PHP file that used the include statement.
The include function used when we use same menu or header on multiple pages of a website.

PHP include() syntax:

include  ‘ filename’;

PHP include Example

We have a same header for all website pages so create “header.php” file like:

For include header file in all pages , use include statement like:

The output of include() example:

PHP include() function

PHP include() function example

Example

We have same menu on all website pages, create “menu.php” file like:

We use above menu on all web pages. use include statement to display “menu.php” file on all pages.

The output is :

PHP include() function example

PHP include() function example


The PHP require() Function

The require() function copy all the text from one php file into another php file that uses the require() function.
In require() function there is a problem with file then the require() function generate fatal error and stop execution of code.
while the include() function will continue to execute script.

The require() function is better than the include() function, because scripts not to be continue if file has problem or missing.

The above include() function example generate same result for require() function.

Here, we will take an php example to understand difference between require() and include() function.

We try to copy “missing.php” file in to another php file using require() and include() function.
The “missing.php” file does not exists.

For include() function

The output of include() function is :

The first page of site

The above same example we use require() function incited of include() function.

For require() Function

The output will be nothing.

Leave a Reply

Your email address will not be published. Required fields are marked *

7 + 3 =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">