LERAN PHP COMPLETE

Learn one of the most powerful programming languages in the world and become a rockstar developer.

File Inclusion


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 included one PHP file into another PHP file.

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

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.

include 'filename';
or
require 'filename';

PHP include Examples

Assume we have a standard menu file called "menu.php", that looks like this:

<div class="menu-class">
    <a href="/tutorials/index.php">Home</a> 
    <a href="/tutorials/html/html-introduction">HTML Tutorial</a>
    <a href="/tutorials/css/index.php">CSS Tutorial</a>
    <a href="/tutorials/javascript/index.php">JavaScript Tutorial</a>
    <a href="/tutorials/php/index.php">PHP Tutorial</a>
</div>

<?php
    echo 'this is the menu file and we incude this file to all pages';
?>

All pages in the Web site should use this menu file. Here is how it can be done (we are using a

element so that the menu easily can be styled with CSS later):

<html>
    <body>
        <div class="menu">
            <?php include 'menu.php'; //this include menu.php file contents here ?>
        </div>
        
        <h1>Welcome to my home page!</h1>
        <p>Some text.</p>
        <p>Some more text.</p>
    </body>
</html>

PHP include vs. require

The require statement is also used to include a file into the PHP code.

However, there is one big difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute:


x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine