Difference between require, include, require_once and include_once?

 

In PHP, require, include, require_once, and include_once are used for including external files into your PHP script. They serve similar purposes, but there are key differences between them:

  1. require: It is used to include a file, and if the file is not found or there is an error, it will stop the script execution and generate a fatal error.

    php
  • <?php require 'file.php'; echo 'This will only be executed if file.php exists and is valid.'; ?>
  • include: It is used to include a file, but if the file is not found or there is an error, it will only generate a warning and continue script execution.

    php
  • <?php include 'file.php'; echo 'This will be executed even if file.php is not found or has errors.'; ?>
  • require_once: It is similar to require, but it checks if the file has already been included, and if so, it won't include it again. This prevents multiple inclusions of the same file.

    php
  • <?php require_once 'file.php'; require_once 'file.php'; // This won't include file.php again. ?>
  • include_once: Similar to require_once, it includes a file, but checks if it has already been included, and if so, it won't include it again.

    php
    1. <?php include_once 'file.php'; include_once 'file.php'; // This won't include file.php again. ?>

    In summary:

    • Use require or require_once when you want to include a file that is crucial for your script's functionality. If the file is missing or has errors, it will halt the script.
    • Use include or include_once when you want to include a file that is not crucial, and you want the script to continue running even if the file is missing or has errors.

    Remember to use these statements appropriately based on your application's requirements, and handle error cases accordingly.

    Comments