Sascha's Digital Drawer

PHP 101: Include vs Require

In the world of PHP, there are often twelve ways to do the exact same thing. But when it comes to pulling one file into another, you usually have two main contenders: include and require.

On the surface, they seem identical. They take the code from file_a.php and dump it into file_b.php. But when you’re building a system, the choice between them comes down to one question: How catastrophic is it if this file goes missing?

The Crash Test

Let’s walk through the failure modes.

Scenario A: The include Approach

include "non_existent_file.php";
echo "I am still alive!";

If you use include, PHP throws a E_WARNING.

  • The Result: The script screams a little bit (check your logs), but it keeps going. The echo statement executes.
  • The User Experience: They might see a broken page with a missing sidebar, or a layout that looks a bit wonky, but they see something.

Scenario B: The require Approach

require "non_existent_file.php";
echo "I am dead.";

If you use require, PHP throws a E_COMPILE_ERROR (Fatal Error).

  • The Result: Immediate termination. The script stops dead. The echo statement never happens.
  • The User Experience: A white screen of death, or your custom 500 error page.

The Decision Matrix

So, which one do I use? I run a simple mental check:

  1. Is this file essential for the application to run?

    • Database connection credentials? Require. If I can’t talk to the DB, there is no page to render. Crash it.
    • Core authentication logic? Require. I don’t want a page loading in a half-broken, potentially insecure state.
    • The main 404 template? Require.
  2. Is this file “nice to have”?

    • A tracking pixel snippet? Include. If the tracking server is down or the file is missing, I don’t want to kill the user’s checkout flow just because I can’t track them.
    • A dynamic sidebar widget? Include. Even if the “Recent Posts” widget fails to load, the user can still read the article.

Summary

  • require says: “I cannot exist without this.”
  • include says: “It would be nice if this was here.”

Understanding this distinction is the first step in defensive programming. Don’t let a missing footer file crash your entire payment gateway.

← Back to all posts