How To Include File in PHP

You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to include file in php into another PHP file.

Syntax :

This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

  • The include() Function
  • The require() Function

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Assume you want to create a common menu for your website. Then create a file menu.php with the following content.

Example

Assume we have a menu file called “menu.php”:

All pages in the Web site should use this menu file. Here is how it can be done

It will produce the following result–

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.

This will produce the following result –

Trust this instructional exercise helped you a lot, keep reading our various posts for more coding Tricks and Tips. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub