Categories
PHP

Including Files in PHP – Learn PHP in 7 Days – Day #6

Include Function

Including files bring more convenience in managing your code. As the name states, include is a function that will simply dump the contents of the included file into the current file. This is cool because some times you may need some code that should be available on all pages. Say a menu or a website header.

Including files saves a lot of efforts by writing your code multiple times on each page. Yeah I know you copy and paste but that requires some more efforts too comparatively. Suppose you suddenly add a page in menu. Then? You need to update all the files. Using include function we can just create one file and include it all over in other files. Hence editing only one file will modify code in your other files.

I hope I am clear enough in explaining this to you. Let us start with an example. Oh before that, the syntax for include function is

<?php include("filename.php"); ?>

So let us first create a file called menu.php The file content would be something like this.

<a href="#">Home</a> -
<a href="#">About Us</a> -
<a href="#">Contact Us</a> <br />

Now let us create an index.php file. The index.php file will contain some content as well as the menu file. So this is what the code will be in index.php file

<html>
<head>
<title>Testing Include File</title>
<head/>
<body>
<?php include("menu.php"); ?>
<p>This page is created to display the working of include  function</p>
</body>
</html>

See the preview

7-include

Require Function

The require function is almost same as the include function. The only difference is in error handling. When the included file doesn’t exist, a warning is displayed and the execution is preceded.

Where as when a file included via require function does not exist, then a fatal error is displayed and the execution is halted at the same line. The syntax is

<?php require(“filename.php”); ?>

Related posts:

  1. MS DOS Tutorials – How to Create, Append and View Files and Move Files and Directory
  2. Handling Traffic With Custom 404 Error Pages
  3. PHP Syntax, Variables, Echo Statement – Learn PHP in 7 Days – Day #1
  4. Learn PHP in 7 Days
  5. MS DOS Tutorials – How to Create, Delete, Change, Rename Directory and Files