↓ Archives ↓

PHP include vs. require

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

The difference between include() vs. include_once() or 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 in fact more significant difference is, between 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 seem to avoid 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.

So in a normal scenario, where you want the execution to go on and show users the output, even if a file is accidentally missing (or perhaps it's the part of the Programming Logic), use include() or include_once().

On the other hand, in case of FrameWork, CMS or a complex PHP application coding, always use require() or require_once() to include a key file 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 proper Error Handler to show appropriate data.

For more information see PHP manual or this online resource.

by Fayaz Ahmed

Share | Bookmark this article (Use the buttons below) ↓

23 Comments | Pings

  • May 24th 201011:05
    - janlon

    Reply

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

    Thanks

  • May 25th 201018:05
    - fayazmiraz

    Reply

    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.

  • May 26th 201006:05
    - mario

    Reply

    "require()" is shorthand for "include() or die()"

    • May 26th 201009:05
      - fayazmiraz

      Reply

      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.

  • Jun 1st 201022:06
    - Kobyn

    Reply

    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.

    • Jun 2nd 201001:06
      - fayazmiraz

      Reply

      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.

  • Jun 2nd 201008:06
    - kobyn

    Reply

    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.

    • Jun 2nd 201014:06
      - fayazmiraz

      Reply

      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.

  • Jun 3rd 201008:06
    - Kobyn

    Reply

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

  • Jun 28th 201021:06
    - borg

    Reply

    You definitely got the point, but callig that article 'advanced' is a bit too much.

    • Jun 28th 201023:06
      - fayazmiraz

      Reply

      Nothing is advanced once you know it :) .

      BTW, I didn't call it 'advanced', just tagged it within advanced PHP section.

  • Jul 18th 201011:07
    - Aafrin

    Reply

    hey there,
    I personally am a php newb and your post has indefinitely helped me in tweaking my wordpress better. =D
    thank you alot.

  • Oct 3rd 201023:10
    - Fraz Ahmed

    Reply

    Hi,

    It is very common among new PHP developers to be confused for using include over require, echo over print, single quote over double quote.

    You shared a good amount of knowledge on this topic. I also wrote an article for the same at:

    http://www.techmug.com/php-basics-for-beginners/

  • Dec 9th 201004:12
    - Mia

    Reply

    Loved the tutorial mate, just what i was looking for.

  • Jan 19th 201118:01
    - vijaya kumar

    Reply

    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

    • Jan 19th 201118:01
      - fayazmiraz

      Reply

      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);

  • Feb 2nd 201119:02
    - madnip

    Reply

    what is the different bet php & advance php.how can I learn advance php?

    • Feb 3rd 201115:02
      - fayazmiraz

      Reply

      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.

  • May 16th 201109:05
    - tom89

    Reply

    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.

  • Sep 14th 201100:09
    - Akif Shamim

    Reply

    "require()" is shorthand for "include() or die()" :)

    • Oct 1st 201115:10
      - Fayaz Ahmed

      Reply

      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 :)



  • This Post is Recommended by:

    » Really Useful Tutorials You Should Have Read in May 2010 | PIXEL SHOP
    » The powerful web | Fast, Easy, Complicated, and Powerful Web

    Leave a Reply