Core PHP 7 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Insert the content of one PHP file into another with include and require.
  • Explain how include and require differ when a file is missing.
  • Use include_once and require_once to avoid loading a file twice.
  • Build a site with a common header, menu and footer.
Server Side Includes

You can insert the content of one PHP file into another PHP file before the server executes it, with include or require. The two are identical in every way except how they handle errors:

  • include (or include_once) generates a warning, but the script continues execution.
  • require (or require_once) generates a fatal error, and the script stops.

These statements are used to put functions, headers, footers or other elements that are reused on many pages into separate files. Server side includes save a lot of work: you create a standard header, footer or menu file once for all your web pages. When the header needs to be updated you change only the include file; when you add a new page to your site you change only the menu file instead of the links on every page.

include and require are language constructs, so the parentheses are optional: include "header.php"; and include("header.php"); are the same.

The include Statement

include takes all the content of the specified file and includes it in the current file. If an error occurs, it generates a warning and the script continues.

Assume that you have a standard header file called header.php:

File: htdocs/phpbook/ch13/header.php
<div style="background:#173b6c;color:#fff;padding:6px">
  <b>PHP Training Institute</b> – Bhopal
</div>

To include the header file in a page, use include:

File: htdocs/phpbook/ch13/home.php
<html>
<body>
<?php include "header.php"; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch13/home.php
PHP Training Institute – Bhopal
Welcome to my home page!

Some text.
A common menu file

Assume we have a standard menu file, menu.php, that should be used on all pages:

File: htdocs/phpbook/ch13/menu.php
<a href="default.php">Home</a> |
<a href="tutorials.php">Tutorials</a> |
<a href="references.php">References</a> |
<a href="examples.php">Examples</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>

All pages of the web site include this menu file:

File: htdocs/phpbook/ch13/page.php
<html>
<body style="font-family:Arial;font-size:13px">
<div class="leftmenu">
<?php include "menu.php"; ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch13/page.php
Browser output
Home | Tutorials | References | Examples | About Us | Contact Us
Welcome to my home page.

Some text.

If you look at the source code of the page in the browser (View Source), the menu file's content appears where the include statement was – the visitor cannot tell that it came from another file:

View Source of page.php in the browser
<html>
<body style="font-family:Arial;font-size:13px">
<div class="leftmenu">
<a href="default.php">Home</a> |
<a href="tutorials.php">Tutorials</a> |
...
<a href="contact.php">Contact Us</a>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
The require Statement

require is identical to include, except that it handles errors differently: if an error occurs, include produces a warning and the script continues, while require produces a fatal error and the script stops.

Error example – include
File: htdocs/phpbook/ch13/test_include.php
<html>
<body>
<?php
include "wrongFile.php";
echo "Hello World!";
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch13/test_include.php
Warning: include(wrongFile.php): Failed to open stream: No such file or directory in /opt/lampp/htdocs/phpbook/ch13/test_include.php on line 4

Warning: include(): Failed opening 'wrongFile.php' for inclusion (include_path='.:/usr/share/php') in /opt/lampp/htdocs/phpbook/ch13/test_include.php on line 4
Hello World!

Notice that the echo statement is executed, because a warning does not stop the script.

Error example – require

Now let us run the same example with require:

File: htdocs/phpbook/ch13/test_require.php
<html>
<body>
<?php
require "wrongFile.php";
echo "Hello World!";
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch13/test_require.php
Warning: require(wrongFile.php): Failed to open stream: No such file or directory in /opt/lampp/htdocs/phpbook/ch13/test_require.php on line 4

Fatal error: Uncaught Error: Failed opening required 'wrongFile.php' (include_path='.:/usr/share/php') in /opt/lampp/htdocs/phpbook/ch13/test_require.php:4 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/phpbook/ch13/test_require.php on line 4

The echo statement is not executed, because script execution stopped after the fatal error.

Which one should I use?

Use require (or require_once) for files the page cannot work without – configuration, database connection, function libraries and classes. Use include for optional parts such as an advertisement box or a sidebar, where the rest of the page should still be shown if the file is missing.

include_once and require_once

include_once and require_once behave like include and require, but if the file has already been included they do not include it again. This prevents errors such as "Cannot redeclare function" when a library is included from several places.

File: htdocs/phpbook/ch13/functions.php
<?php
function rupees($amount)
{
    return "Rs. " . number_format($amount, 2);
}
File: htdocs/phpbook/ch13/once.php
<?php
require_once "functions.php";
require_once "functions.php";   // ignored – already loaded
echo rupees(1250) . "<br>";
echo "Included files:<br>";
foreach (get_included_files() as $f) {
    echo basename($f) . "<br>";
}
?>
OUTPUT browser · http://localhost/phpbook/ch13/once.php
Rs. 1,250.00
Included files:
once.php
functions.php
Including Files that Return Values

An included file can return a value. This is a neat way to keep configuration in its own file:

File: htdocs/phpbook/ch13/config.php
<?php
return [
    'site'   => 'PHP Training Institute',
    'db'     => 'phpbook',
    'perpage'=> 10,
];
File: htdocs/phpbook/ch13/useconfig.php
<?php
$config = require "config.php";
echo "Site: {$config['site']}<br>";
echo "Database: {$config['db']}<br>";
echo "Records per page: {$config['perpage']}";
?>
OUTPUT browser · http://localhost/phpbook/ch13/useconfig.php
Site: PHP Training Institute
Database: phpbook
Records per page: 10
A Complete Page Layout

Most PHP web sites split each page into a header, the page content and a footer:

File: htdocs/phpbook/ch13/layout_header.php
<!DOCTYPE html>
<html><head><title><?= $title ?? 'My Site' ?></title></head>
<body style="font-family:Arial;font-size:13px">
<div style="background:#173b6c;color:#fff;padding:6px"><b>My Site</b></div>
File: htdocs/phpbook/ch13/layout_footer.php
<div style="border-top:1px solid #999;margin-top:10px;font-size:11px">
  &copy; <?= date("Y") ?> My Site. All rights reserved.
</div>
</body></html>
File: htdocs/phpbook/ch13/about.php
<?php
$title = "About Us";
require "layout_header.php";
?>
<h2>About Us</h2>
<p>We teach PHP and MySQLi with hands-on projects.</p>
<?php require "layout_footer.php"; ?>
OUTPUT browser · http://localhost/phpbook/ch13/about.php
Browser output
Key Takeaways
  • include and require insert another file's content before execution.
  • A missing file: include → warning, script continues; require → fatal error, script stops.
  • Use require/require_once for essential files, include for optional parts.
  • include_once/require_once load a file only once.
  • Common headers, menus and footers kept in include files make sites easy to maintain.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch13 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : The technique of inserting the contents of one file into another before the server executes it, using include or require, so that common parts are written once and reused.

Answer : Both insert a file, but if the file cannot be loaded include issues a warning and the script continues, while require issues a fatal error and the script stops.

Answer : include only produces a warning, which does not stop execution; require produces a fatal error, which terminates the script.

Answer : Code is written once and reused; a change (e.g. to the menu) is made in one place for the whole site; pages become shorter and easier to maintain.

Answer : It works like include but does nothing if the file has already been included in the current script, preventing redeclaration errors.

Answer : For essential files that may be referenced from several scripts, such as a function library, class file or database connection file.

Answer : A fatal error "Cannot redeclare function …", because the same function would be defined twice.

Answer : No. include and require are language constructs, so include "file.php"; and include("file.php"); are equivalent.

Answer : An array with the full paths of all files that have been included or required so far, including the main script.

Answer : By using a return statement at its top level; for example $config = require "config.php"; receives the array returned by config.php.

Answer : Only the final combined output; the included file's HTML appears where the include statement was, and the include itself is not visible.

Answer : include – if the advertisement file is missing, the rest of the page is still displayed.

Answer : In the directories listed in the include_path setting (usually including the current directory "."), and then in the calling script's own directory.

Answer : Yes. Any text outside <?php … ?> is output as it is, so an include file may contain pure HTML, pure PHP, or a mixture.

Answer : To avoid sending accidental white space after ?> to the browser, which could break header(), setcookie() or session_start().
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. If the included file is missing, include produces a:

Show Answer

Correct Answer : B. Warning
include warns and continues.

Q2. Which statement stops the script when the file cannot be loaded?

Show Answer

Correct Answer : C. require
require raises a fatal error.

Q3. require_once prevents:

Show Answer

Correct Answer : A. Loading a file more than once
It skips files that have already been loaded.

Q4. Which is the best choice for a database connection file?

Show Answer

Correct Answer : B. require_once
The page cannot work without it and it should load only once.

Q5. What does $c = require "config.php"; store in $c?

Show Answer

Correct Answer : C. The value returned by config.php
An included file can return a value to the caller.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – include. https://www.php.net/manual/en/function.include.php
  2. The PHP Group. (n.d.). PHP Manual – require. https://www.php.net/manual/en/function.require.php
  3. The PHP Group. (n.d.). PHP Manual – require_once. https://www.php.net/manual/en/function.require-once.php
  4. The PHP Group. (n.d.). PHP Manual – get_included_files. https://www.php.net/manual/en/function.get-included-files.php