PHP include vs require vs include_once vs require_once

PHP programmers regularly use the functions (or more appropriately language constructs) like include, include_once, require and require_once to insert useful codes in the flow of execution. Although these constructs are used quite interchangeably, there are actually significant differences among them. Although these differences are very well defined in PHP manual, I've noticed many programmers don't really consider these differences while coding. I hope this post will help them towards a better coding practice

The difference include vs include_once and require vs require_once is obvious. include and require allow you to insert a file multiple times within a single execution lifetime. On the other hand, include_once and require_once make sure one file is inserted only once in a single execution lifetime, even if your CODE calls them multiple times.

Ironically, a little less obvious (and possibly more significant) difference is: include vs require or include_once vs require_once. Even though PHP's naming of these constructs are almost perfect according to their functionality, many PHP programmers, specially the beginners fail to realize the significant difference.

As the name suggests, with include, you simply include other files in the flow of execution. On the other hand, when you use require, you not only include the file in the flow of execution, but also you tell PHP that the execution cannot be proceeded without this file. In more technical terms:

If PHP interpreter fails to include a file in response to a call of include or include_once, a Warning in generated and execution continues without that file. Where as, failure to include a file called by require or require_once generates a Fatal Error and execution stops there.

Sometimes people compare require with include or die(). However, that is not entirely correct as well. Because include 'file' or die() will not generate Fetal Error, but require 'file' will, if the file is missing or unreadable.

So in a normal scenario, where you want the execution to go on and show users the output, even if the file is accidentally missing or unreadable, use include or include_once.

On the other hand always use require or require_once to include key files to the flow of execution. This will help avoid compromising your application's security and integrity,  just in-case one key file is accidentally missing. Then use error_reporting(0) to suppress all the errors and use proper Error Handler to show appropriate information.

For more information checkout PHP manual.

23 comments on “PHP include vs require vs include_once vs require_once”

  1. Great articles.
    Pls explain more, when to use include or require once or include or require many times.

    Thanks

  2. Normally, to include files that contain function definition, class definition, global variable that is used in other files etc. we should always use include_once or require_once. Since, multiple inclusion of these files may generate Error or unexpected behavior.

    On the other hand, files that normally generate output, that may be placed in multiple sections of a page, should be included using include or require. For example: ad. content, breadcrumb, paging content, tag cloud etc.

    There can be many other scenarios, but if you get the basics right, then you'll know when to use what.

    1. Functionally it is very close, but still not the same. Since "include() or die()" will never generate a Fetal Error, but "require()" will.

      So, in an Advanced PHP application, where you'll have your customized Error Handler (which perhaps does some additional task when "Fetal Error" occurs), they will produce different results.

  3. I am trying to include my header.php for all my website environment. Unfortunately calling the header.php trough include or require from any subfolder different than the root folder does not work at all. How to solve this issue? Thank you in advance for all your support.

    1. There are many ways to do this, but for simplicity try this:
      include("../header.php");

      when you add a "../" before file, it means PHP will look for that file one directory ahead of current include directory.

      Similarly. if you are two directory below, then add two "../", for example:
      include("../../header.php");

      This is true for almost all programming languages, not just PHP.

  4. Hi Fayaz, Thank you for your promply response. You are right about the include. Actually it works fine when the php file doesn't have any other relatives paths like css or js calls and it is even worse when the php file has a swf file embedded. That's my case I got a header for all my website which includes the css style file, a javascript file and a flash (swf) animation. I got for example a subfolder named root/artists/artist.php and I want to include my php header file located in root/includes/header.php. Using include (../includes/header.php) in artist.php) doesn't work properly. That's why after some research I did find that I have to use absolute path (require_once (dirname (__FILE__) . '/../includes/header.php') in my artist.php file. Right now is better the performance because the css style is working fine but I have the problem now with the swf file which doesn't show the animation. Any thoughs?
    Thanks.

    1. Hi kobyn,

      Interesting, that's why it's hard to provide the correct solution without looking into the code. I'm sharing some thoughts with you, but if it still doesn't resolve your problem, you can send me your code to my email. I'll take a look.

      Anyways, what I see from your comment, there might actually be two problems:

      1. You are right about using absolute path. But most probably, you are missing one key point: context of include() or require().

      When you are including "root/includes/header.php" from "root/artists/artist.php", the PATH context still is "root/artists/". So, in case you include any file in header.php, context will be changing depending on the file from where header.php is included. So that will break any other include you make from header.php.

      To resolve this, in header.php, (A) include all the files using absolute PATH of header.php itself OR (B) change directory context when you are inside header.php.

      So header.php will have code either like (A) or (B):

      (A) [using real path of header.php]
      $header_path = "YOUR_REAL_HEADER_PATH";
      ....
      include_once($header_path . '/../path1/file1.php');
      include_once($header_path . '/../path2/file2.php');
      ....

      (B) [changing file include context]
      // at the beginning of header.php
      $tmp_dir = getcwd();
      chdir(realpath(dirname(__FILE__)));

      ....
      // from here all file include directory context is "/root/includes/"
      // so include other files (if any) according to this current directory of "header.php".
      ....

      // at the end of header.php
      chdir($tmp_dir);

      2. Relative PATH and Relative URL (llnk) are not the same thing and they are completely independent from each other.
      So if I take your example: when you are including header.php from "/artists/artist.php", let's say you have a CSS link from in header.php like this:

      <link rel="stylesheet" href="css/style.css" type="text/css" />

      This has nothing to do with the include() you used in artist.php to include your header file "header.php". Rather, the problem occurs when the browser tries to load your css file. In case of your home page, browser will try to load the css file from "http://your_site/css/style.css" and in case of "/artists/artist.php", browser will try to load it from "http://your_site/artists/css/style.css".

      I'm not sure if this is the problem in your case, but if it is, then to solve it, the best way is to use absolute URL to include your resources.

      So, in your header.php include all your resources, preceding by your site address. For example:

      <?PHP
      $base_url = 'http://' . $_SERVER['HTTP_HOST'];
      ?>
      <link rel="stylesheet" href="< ?PHP echo $base_url;?>/css/style.css" type="text/css" />

      ----------------------------
      I hope this helps.

  5. Thank you for all your support. Right now I have a better idea for using absolute paths. My app is working fine now. Saludo..

  6. i have a problem when using on home page. every include files not working. i used many include files on the index.php, but it doesn't showing header nav content sidebar and footer.php's. it showing empty page only

    1. Hi Vijaya,

      Can you provide a little more details about your problem? Or perhaps a sample link?

      Normally, PHP shows error if it is unable to include a file. Make sure error reporting is on (use the following CODE) and PHP should point out the problem.

      // use this CODE at the very beginning of index.php and make sure it's not changed anywhere else
      error_reporting(E_ALL);
      ini_set("display_errors", 1);

    1. Actually there is nothing called "advanced PHP". Any topic that amateurs generally avoid, or any best practice that is learnt in time through experience can be considered as advanced.

      Normally, if you can read the complete PHP manual, then you'll learn most advanced stuff. Also go through users' comments in manual.

      Also you can read articles/blog-posts/tutorials from experienced PHP developers and community. Zend Developer Zone is a good place to start.

  7. What if I wanted to keep the PHP file on my server for copyright? This would allow the web application to function whilst allowing me to keep Key Algorithm Source Files on my server.

    1. Nope! Require() also throws fetal error, if failed.

      Where as include() or die() will just stop execution if failed. In advanced programming that makes a lot of difference :)

Leave a Reply

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

You may use the following HTML tags and attributes, but please be nice:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>