Home PHP What is the difference between include and require statements in PHP?

What is the difference between include and require statements in PHP?

Author

Date

Category

In PHP, include and require statements are used to include external files into a PHP script. The main difference between the two is how they handle errors when the file being included is not found.

Here’s a brief explanation of each:

  1. include: include statement includes a file into the PHP script, and if the file is not found, it will generate a warning and continue executing the script. The warning indicates that the included file was not found, but the script execution continues.

Example:

<?php
// Include a file
include "example.php";

// Rest of the code
echo "This line is executed even if example.php is not found.";
?>
PHP
  1. require: require statement includes a file into the PHP script, and if the file is not found, it will generate a fatal error and stop the script execution. The fatal error indicates that the included file was not found and stops the script execution.

Example:

<?php
// Require a file
require "example.php";

// Rest of the code (this code is not executed if example.php is not found)
echo "This line is executed only if example.php is found.";
?>
PHP

So, in summary, require is more strict than include and should be used when the included file is critical for the functioning of the script. include should be used when the included file is not critical and can be omitted without affecting the script’s execution.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts