include

PHP Include and Require

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.