PHP Include vs Require

To include or to require? To include_once or require_once? In designing web pages with PHP there is a good chance you will encounter the need to include other PHP script files or HTML files. Good web design would include a template of some sort which allows pages to share a header, footer, sidebar or other similar facets. In PHP there are several commands that help you include code from another file. These are include, include_once, require, require_once.

Check out the following code segments to see how each option would work.

PHP include

<?php
     // include the code from header.php whenever encountered
     include "header.php"; 
 
?>

PHP include_once

<?php
     // include the code from header.php only the first 
     // time encountered
     include_once "header.php"; 
?>

PHP require

<?php
     // include the code from header.php whenever encountered and fail 
     // if it is not found. Throws fatal E_COMPILE_ERROR.
     require "header.php" 
?>

PHP require_once

<?php
     // include the code from header.php only the first time encountered 
     // and fail if it is not found. Throws fatal E_COMPILE_ERROR.
     require_once "header.php" 
?>

Choosing the correct method is important. If you have a page where you must determine if a user is logged in and that routine is in an external file, then you would want to make sure to use require or require_once to make sure that the page doesn’t execute without that validation passed. If you have a page that displays something relatively unnecessary then an include or include_once might be sufficient.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>