Home » Tutorials » PHP » Include and Require

Include and Require

Have you ever written some HTML code that was exactly the same across multiple pages, like a header or a footer? Your life is about to get so much easier. These awesome creatures known as PHP Server Side Includes will save you so many headaches and keystrokes later.

It is generally good practice to use the include function when writing code, and then later as you review it to replace it with the require function. Based on their overall purpose, they do exactly the same thing. They both “include” a file such as another PHP file that includes a standard header for your website. This is entirely like writing it out manually on each page. However, the difference between the two functions is that the require function stops executing your code as soon as an error occurs. The include function would still continue executing. Running the rest of the code after an error is usually not a good idea, so use require.

Using Include and Require

Example
//requireExample.php
    <p>HTML Text</p>
    <?php
        echo "PHP Text";
    ?>
//end of requireExample.php

//Your other PHP file
    <?php
        require("requireExample.php");
    ?>
//end Your other PHP file
Result

HTML Text

PHP Text

How freaking cool is that? You can completely put a navigation menu in a file and reference it using a require. I put PHP code and HTML code in my include to show you that it really doesn’t matter. You can include simple HTML files, PHP files, or a crossbreed of them. You can now require headers, footers, navigation bars, and anything else you don’t want to type more than once.

Let me just say a small precautionary note really quick. Don’t go too overboard. I have worked on various sites where I had to go through the requires of 6 pages to correct an error. Try to just have includes for the header, footer, navigations, and a few files with commonly used functions.



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Include and Require". After Hours Programming. Accessed on April 24, 2024. https://www.afterhoursprogramming.com/tutorial/php/include-and-require/.

  • Stewart, Suzy. "Include and Require". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/php/include-and-require/. Accessed 24 April, 2024.

  • Stewart, Suzy. Include and Require. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/php/include-and-require/.



Leave a Comment

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