Differentiate between require and include?

Require and include both are used to include a file, but if data is not found include sends warning whereas require sends Fatal error.

In PHP, both require and include are used to include and evaluate the specified file in the current script. However, there are differences between them:

  1. Error Handling:
    • require will cause a fatal error (E_COMPILE_ERROR) and halt the script execution if the specified file is not found or cannot be included.
    • include will only produce a warning (E_WARNING) and continue script execution if the specified file is not found or cannot be included.
  2. Usage:
    • require is used when the included file is essential for the operation of the script. If the file is not found or cannot be included, the script should not continue execution.
    • include is used when the included file is not essential for the operation of the script. If the file is not found or cannot be included, the script can still continue execution.
  3. Return Value:
    • require returns a fatal error if the file cannot be included.
    • include returns true if the file is included successfully and false otherwise.

Usage Examples:

php
// Using require
require 'essential_file.php'; // If file not found, script execution halts
// Code continues here

// Using include
include 'optional_file.php'; // If file not found, script continues execution
// Code continues here

In summary, use require when the included file is crucial for the script’s operation and any failure to include it should halt script execution. Use include when the included file is optional, and script execution can continue even if the file is not found or cannot be included.