PHP: Include vs. Require

Both are used to include external file to the script.

Include

When the file we are trying to include does not exist or the permission is incorrect, this will give you a warning and continue the script.

<?php

include 'something.php';

echo 'test';

=> Warning: include_once(something.php): Failed to open stream: No such file or directory in /var/www/html/include.php on line 3
=> test

Require

When the file we are trying to include does not exist or the permission is incorrect, this will give you a warning, throw an Error, and terminate the script.

<?php
  
require 'something.php';

echo 'test';

=> Fatal error: Uncaught Error: Failed opening required 'something.php' (include_path='.:/usr/local/lib/php') in /var/www/html/require.php:3
=> Stack trace:
=> #0 {main}
=>   thrown in /var/www/html/require.php on line 3

Error Handling

For warning suppresion we can set the runtime configuration with:

<?php
// show nothing
error_reporting(0);
// show everything
error_reporting(-1);

For error suppresion, we catch the exception with try-catch block:

<?php
try {
  require 'require.php';
}
catch (Error $e) {
  echo $e->getMessage();
}

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *