Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. PHPBeginner - Differences Between include() and require()

Differences Between include() and require() - Images: Japanese

It's the height of summer as I'm writing this, yet today feels oddly cold. After 20-some years of desk work, my body just can't keep up with sudden temperature swings anymore.

Anyway, hey everyone!

Last time we covered variables in quite a bit of detail. The recent articles have been a little on the dry side, so today I'd like to show off some of PHP's real power and convenience.

We're talking about what I call 'include processing'. It's incredibly useful. Fair warning — that's not an official term, just something I made up.

(Though honestly, if you say 'include processing', most people will know what you mean.)

'Include' (include) literally means "to contain" or "to bring in", and in programming, 'include' means something like 'pull in the contents written in another file'. That part is the official definition — apologies if I've got it slightly off.

Now, we're assuming everyone reading this article is already comfortable writing HTML, so let's do a quick HTML refresher.

Basic HTML looks something like this:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Content goes here -->

</body>
</html>

HTML has a head element, and above that there's the doctype declaration. That whole block tends to be almost identical across all your pages — specifically this part:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head>

If your site is built purely with HTML files, changing something like the path to your CSS file means you'd have to update every single HTML file. If you had millions of pages, that would be a nightmare. You could do a batch find-and-replace, but that's risky if something goes wrong — not something you want to rely on.

With a PHP-based dynamic website, however, you can use include() and similar functions to pull in partitioned HTML files and output them together. Let's build that out.

First, create a file called header.php. You can name it anything, but if it contains the head element and similar markup, header.php is the convention most people go with. Write your doctype declaration and head element content into this file.

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head>

Save that file and set it aside.

Next, create a file called 'index.php' in the same folder (directory). This will be your main PHP file. If you want it to show up as the top page, naming it 'index.php' is the way to go. The directory location doesn't matter much, but keeping both files in the same place makes things easy to follow. Write the remaining HTML into 'index.php'.

<body>
<!-- Content goes here -->

</body>
</html>

Then, add include('./header.php'); at the top of index.php, like this:

<?php
include('./header.php');
?>
<body>
<!-- Content goes here -->

</body>
</html>

Now, when you access index.php, something neat happens — the following text is returned:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head><body>
<!-- Content goes here -->

</body>
</html>

The source code comes back looking almost identical to our original HTML file. That's include processing in action. Now if you ever need to change the CSS file path, you just tweak 'header.php' in one place and the change is reflected across every page on the site. Pretty handy, right?

Let's now go through PHP's include functions properly. It gets a little involved, but there are actually four functions that handle include processing in PHP: 'include()', 'require()', 'include_once()', and 'require_once()'. Each one behaves slightly differently, so let's take a look.

PHP has quite a few similar-sounding functions, so watch out for that.

The basic syntax for all of them is the same — just pass the file path as a string inside the parentheses. It doesn't have to be a '.php' file either; you can load '.txt' files just fine. For example, to include './header.php', you'd write any of the following:

<?
include('./header.php');
require('./header.php');
include_once('./header.php');
require_once('./header.php');

Now, the difference between include() and require() comes down to what happens when a file fails to load. With 'include()', if the file can't be found, only that include statement is skipped — everything after it continues running as if nothing happened.

With 'require()', on the other hand, a failed load immediately triggers a fatal error and stops all further execution.

Let's see it in action. We'll try to load a non-existent file ./test.php using include().

<?php
include('./test.php');

echo 'test!';

Here's what comes back (assuming error output is set to 'On' in php.ini):

Warning: include(./test.php): failed to open stream: No such file or directory in /Users/xxxx/Desktop/test/index.php on line 2

Warning: include(): Failed opening './test.php' for inclusion (include_path='.:/Applications/MAMP/bin/php/php5.6.7/lib/php') in /Users/xxxx/Desktop/test/index.php on line 2
test!

There are warnings, but notice that test! is still output at the end.

Now let's switch to 'require()' and see what changes:

<?php
require('./test.php');

echo 'test!';

Warning: require(./test.php): failed to open stream: No such file or directory in /Users/xxxx/Desktop/test/index.php on line 2

Fatal error: require(): Failed opening required './test.php' (include_path='.:/Applications/MAMP/bin/php/php5.6.7/lib/php') in /Users/xxxx/Desktop/test/index.php on line 2

Unlike include(), test! never appears. With require(), the entire script stops right there — including everything that comes after it.

At first glance, the more flexible 'include()' might seem like the obvious choice. But when you're loading a PHP file that contains critical logic, you absolutely need that file to load — and 'require()' makes sure you notice immediately if it doesn't.

So a common approach is: use include() for ordinary HTML or text files where a load failure isn't a big deal, and use require() for important PHP files containing essential functions or logic. If you're not sure which to use, just ask yourself: is this file critical? If yes, use 'require()'.

Well, of course, the ideal is to never get the file path wrong in the first place...

Now for the other two — 'include_once()' and 'require_once()'. include_once() is include() but it only processes the same file once. require_once() is require() but it only processes the same file once. Simple as that.

Let's experiment. We'll use 'include()' to pull in the same 'header.php' twice in 'index.php'.

<?php
include('./header.php'); // Include it twice and see what happens.
include('./header.php');
?>
<body>
<!-- Content goes here -->

</body>
</html>

Here's what comes back:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head><!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head><body>
<!-- Content goes here -->

</body>
</html>

'header.php' was loaded and output twice. Now let's rewrite it using 'include_once()'.

<?php
include_once('./header.php'); // Trying to include it twice.
include_once('./header.php');
?>
<body>
<!-- Content goes here -->

</body>
</html>

Here's what comes back:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" href="style.css">
</head><body>
<!-- Content goes here -->

</body>
</html>

Even though include_once() appears twice, header.php is only loaded and output once. require_once() behaves the same way. That's the difference between the '_once' variants and their counterparts.

It can feel a bit confusing, so let's summarize how PHP's include processing works.

For files that aren't critical — plain HTML, a small snippet of text, that sort of thing — 'include()' is the right tool. Using 'include_once()' here would mean you can only output that file once, which becomes an annoying limitation if you ever want to display the same content in multiple places on a page.

For example, say you have a 'whatsnew.txt' file with the latest news, and you're pulling it in with 'include_once()' to display it at the top of each page. Then you decide, "I want to show this at the bottom of the page too." You'd have to rewrite all those 'include_once()' calls back to 'include()'. If you've got hundreds of pages, that's a painful fix. So 'include_once()' is one you'll rarely have a reason to reach for.

For essential files — PHP files containing function definitions, critical logic, things that absolutely must be loaded — use require_once(). It fails loudly if the file is missing, so problems are easy to catch.

"Why 'require_once()' and not just 'require()'?" Good question. Files containing function definitions and shared logic generally don't need to be loaded more than once. Redefining the same function multiple times is odd, and loading a file like that more than once can cause functions to get overwritten, leading to bugs that are hard to track down.

This is especially worth keeping in mind for JavaScript files. Since JavaScript runs in the browser, variables and functions are live as long as the page is open. If a JavaScript file gets loaded multiple times by mistake, it can produce bizarre behavior that's very hard to diagnose — especially for server-side developers who aren't as comfortable with JavaScript. With 'require_once()', even if you accidentally write the include twice, the file only loads once, so you're protected.

Sure, "just never make that mistake" seems like the obvious answer.

But in large websites or browser-based games, files get broken up into so many pieces that it becomes hard to keep track of everything.

Accidentally writing the same include twice happens more often than you'd think.

So here's the quick summary: for simple file loading, use 'include()'. For critical file loading, use 'require_once()'.

That's it!

Sorry this one ran a bit long. Even for simple websites, include processing is genuinely useful. This site uses it extensively — when I want to tweak a design in a certain area, fixing it in one place updates every page that uses it. Maintenance becomes a breeze.

Nice work getting through this one! In the next article, we'll play around with 'operators'. Until then, see you next time!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .