Day 10: Include files In PHP

This is one of the strong feature of PHP that we can include content of one PHP or HTML file into another PHP file. With this feature we can reduce our codes of line and also avoid repentance of code. This can be done With the help of:

  1. include() function
  2. require() function
  3. include_once() function
  4. require_once() function

Program 35: Example of include().

Create 2 files (both should be in same folder)

var.php

<?php
$pi = 3.14;
$shape = “circle”;
?>

area.php

<?php
include “var.php”;
$radius = 3;
echo “Shape is “.$shape;
echo “<br>Area = “.$pi*$radius*$radius;
?>

OUTPUT :
Shape is circle
Area = 28.26


Explanation: variable “$pi” and “$shape” defined in “var.php” and used in “area.php” with the help of include function.


Program 36: Example of require().

Create 2 files

menu.php

<a href=”http://bestonetechnologies.com”>HOME</a> |
<a href=”http://bestonetechnologies.com/about-me”>ABOUT</a> |
<a href=”http://bestonetechnologies.com/contact-us”>CONTACT US</a>

home.php

<?php
require “menu.php”;
echo “<br>Welcome to home page.”;
?>

OUTPUT :
HOME | ABOUT | CONTACT US
Welcome to home page.


Explanation: links are defined in “menu.php” and can include in files where required with he help of require. If we makes any change in “menu.php” then it will reflect all the files where we have included “menu.php”.


Difference between Include and Require.

include throws a warning if the fie is not found and continue with remaining code.

require throws a fatal error if the file not found and program will terminate.


Include_once and require_once is same as include and require function but the difference between include and include_once is :

with include function we can include one file more than once, on other hand include_once include file only once even we have written more than once, same with require and require_once. See below example.

Program 37: Showing difference between include() and include_once().

<?php
include “menu.php”;
echo “<br>Welcome to home page.<br>”;
include “menu.php”;
?>

OUTPUT :
HOME | ABOUT | CONTACT US
Welcome to home page.
HOME | ABOUT | CONTACT US


Explanation:”menu.php” included twice.


<?php
Include_once “menu.php”;
echo “<br>Welcome to home page.<br>”;
include_once “menu.php”;
?>

OUTPUT :
HOME | ABOUT | CONTACT US
Welcome to home page.


Explanation:”menu.php” included once even written twice.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.