O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Including Code

PHP provides two constructs to load code and HTML from another module: require and include. Both load a file as the PHP script runs, work in conditionals and loops, and complain if the file being loaded cannot be found. The main difference is that attempting to require a nonexistent file is a fatal error, while attempting to include such a file produces a warning but does not stop script execution.

A common use of include is to separate page-specific content from general site design. Common elements such as headers and footers go in separate HTML files, and each page then looks like:

<?php include "header.html"; ?>
content
<?php include "footer.html"; ?>

We use include because it allows PHP to continue to process the page even if there’s an error in the site design file(s). The require construct is less forgiving and is more suited to loading code libraries, where the page cannot be displayed if the libraries do not load. For example:

require "codelib.php";
mysub();               // defined in codelib.php

A marginally more efficient way to handle headers and footers is to load a single file and then call functions to generate the standardized site elements:

<?php require "design.php";
header(); ?>
content
<?php footer();

If PHP cannot parse some part of a file added by include or require, a warning is printed and execution continues. You can silence the warning by prepending the call with the silence operator (@)—for example, @include.

If the allow_url_fopen option is enabled through PHP’s ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required