WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Include Files

PHP include and require statements

In PHP, you can insert the contents of a file into a PHP file before the server executes it.

The

include and require statements are used to insert useful code written in other files into the execution flow.

include and require are the same except for different ways of handling errors:

  • require generates a fatal error (E_COMPILE_ERROR), and the script stops executing after the error occurs.
  • include generates a warning (E_WARNING), and the script will continue to execute after an error occurs.

So if you want to continue execution and output results to the user, even if the include file is missing, use include. Otherwise, in frameworks, CMSs, or complex PHP application programming, always use require to reference critical files to the execution flow. This helps increase the security and integrity of your application in the event that a critical file is accidentally lost.

Including files saves a lot of work. This means you can create standard header, footer, or menu files for all web pages. Then, when the header needs to be updated, you only need to update the header include file.

Syntax

include 'filename';

or

require 'filename';

PHP include and require statements

Basic examples

Suppose you have a standard header file named "header.php". To reference this header file in a page, use include /require:

<html>
<head>
<meta charset="utf-8">
<title>welookups Tutorial(welookups.com)</title>
</head>
<body>

<?php include 'header.php'; ?>
<h1>Welcome to my homepage!</h1>
<p>Some text.</p>

</body>
</html>

Example 2

Suppose we have a standard menu file used in all pages.

"menu.php":

echo '<a href="/">Homepage</a>
<a href="/html">HTML Tutorial</a>
<a href="/php">PHP Tutorial</a>';

All pages in the site should reference this menu file. Here's how to do it:

<html>
<head>
<meta charset="utf-8">
<title>welookups Tutorial(welookups.com)</title>
</head>
<body>

<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>Welcome to my homepage!</h1>
<p> Some text.</p>

</body>
</html>

Instance 3

Suppose we have an include file that defines variables("vars.php"):

<?php
$color='red';
$car='BMW';
?>

These variables can be used in the calling file:

<html>
<head>
<meta charset="utf-8">
<title>welookups Tutorial(welookups.com)</title>
</head>
<body>

<h1>Welcome to my homepage!</h1>
<?php 
include 'vars.php';
echo "I have a $color $car"; //I have a red BMW
?>

</body>
</html>