w1coding.comAll tutorials

PHP Include

PHP lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Basics
  5. Operators
  6. Control
  7. Loops
  8. Variables
  9. Functions
  10. Arrays
  11. Superglobal
  12. File
  13. Loops
  14. Date
  15. Loops
  16. Strings
  17. Error
  18. Class
  19. File
  20. Include
  21. Sessions
  22. Mysql
  23. Cookies
  24. Forms
  25. Cookies
  26. Regular
  27. Authenthication
  28. Fileupload
  29. Mvc
  30. Responsive

PHP Include and Require

PHP allows you to include files within your PHP scripts using include and require. The difference is that include produces a warning if the file is not found, while require produces a fatal error.

Using Include

Use include() to include a file in your script:

      
        <?php
          include('header.php'); // Includes the header file
          echo "This is the main content.";
        ?>
      
    

Using Require

Use require() to include a file that must be included, otherwise the script will stop execution:

      
        <?php
          require('config.php'); // Must include config file for the script to run
          echo "This is the main content.";
        ?>
      
    

Activity

Try It Yourself!

Create a PHP script that includes a header and footer for your webpage using include.

Quiz

Quick Quiz

  1. What is the difference between include and require in PHP?
  2. When would you use include instead of require?

Answers: include produces a warning if the file is not found, while require produces a fatal error. Use include when the file is optional.